문제

I have a ksh93 script (but the question is not ksh related).

Currently, I run my script with something like :

./script 2>&1 | tee logfile

I'm wondering what should I had in my script to get exactly the same result (screen output and a logfile containing both STDOUT and STDERR output). Of course, I want to avoid adding '| tee logfile' for each echo/print I do.

Of course, a way to do that could be to wrap my script in another one that simply run './script 2>&1 | tee logfile' but I was wondering if this could be done inside the script itself.

도움이 되었습니까?

해결책 2

One common technique that is somewhat fragile is:

#!/bin/sh
test -z "$NOEXEC" && { NOEXEC=1 exec "$0" "$@" 2>&1 | tee logfile; exit; }
...

This will discard the return value and exit with the value returned by tee. This may or may not be an issue, and may be the desired behavior.

다른 팁

If the current contents of your script is:

command1 arg1
command2 arg2

You can wrap that lot (inside the script) like this:

{
command1 arg1
command2 arg2
} 2>&1 | tee logfile

The { to } code is now a unit of I/O redirection within the script; the I/O redirection at the end applies to all the enclosed commands. It does not create a subshell; any variables set in the commands are available to the script after the I/O redirection.

The { and } are slightly peculiar syntactically; in particular, } must be preceded by a semicolon or newline.

Just place your code in a function and call it.

your_func(){
#your code
}
your_func $@ 2>&1 | tee logfile
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top