How to redirect both stdout and stderr to a file as well as terminal from inside the script.
#!/bin/sh
LOG_FILE="/tmp/abc.log"
exec &> >(tee -a $LOG_FILE)
echo "Start"
echo "Hi" 1>&2
echo "End"
I found above script. But this script works only on bash. With sh shell it gives following error:
./abc.sh: 5: Syntax error: redirection unexpected (expecting word)
I want a script which works with both sh and bash shells.
Best Answer
Yes,
&>
is abash
operator (now also supported byzsh
, whilezsh
always had>&
for the same like incsh
), and>(...)
aksh
operator (now also supported byzsh
andbash
), neither aresh
operator. That unquoted $LOG_FILE where you obviously don't want split+glob here, makes it zsh syntax (the only one of those shells where split+glob is not performed implicitly upon unquoted expansions, though inzsh
, you'd just doexec >&1 > $LOG_FILE 2>&1
).In
sh
syntax, you can do:Or put everything in a function:
In any case, both that and your
zsh
-style approach would end up printing error messages on the same resource as open on stdout. So if someone doesyour-script > out 2> err
,err
will be empty andout
will contain both the normal output and the errors.To make sure the original destination of output and error is preserved, you could do instead:
(untested).