If I understand you correctly, you can't achieve it with subshells.
If you want the output of commandWhichFails
to be sent to logFile.log
, but not the errors from try()
etc., the problem with your code is that redirections are resolved before command execution, in order of appearance.
Where you've put
try false >> "logFile.log" 2>&1
(using false
as a command which fails), the redirections apply to the output of try
, not to its arguments (at this point, there is no way to know that try
executes its arguments as a command).
There may be a better way to do this, but my instinct is to add a catch
function, thus:
last_command=
exitFunc() { echo "EXIIIIIIIIIIIIIIIIT"; } #added ; here
yell() { echo "$0: $*" >&2; }
die() { yell "$*"; exitFunc 111; }
try() { last_command="$@"; "$@"; }
catch() { [ $? -eq 0 ] || die "cannot $last_command"; }
try false >> "logFile.log" 2>&1
catch
Depending on portability requirements, you can always replace last_command
with a function like last_command() { history | tail -2 | sed -n '1s/^ *[0-9] *//p' ;}
(bash), which requires set -o history
and removes the necessity of the try()
function. You can replace the -2
with -"$1"
to get the N th previous command.
For a more complete discussion, see BASH: echoing the last command run . I'd also recommend looking at trap
for general error handling.