I'm not quite sure where that will lead to, but you can do:
alias dummy='sh dummy $?'
the_program_with_errors
dummy
and your dummy
script would contain:
echo $1
An approach without alias
is to use a shell function:
function dummy { sh dummy $? ;}
With that definition you can get the following behaviour (simulated with true
, false
, and a subshell process):
$ true
$ dummy
0
$ false
$ dummy
1
$ (exit 42)
$ dummy
42
Because the last command executed (the echo
) succeeded. If you want to group the commands, it's clearer to use an if
statement:
if ! step 1 ; then
echo >&2 "Failed to execute step 1"
exit 2
fi
You could also group the error message and exit with { ... }
but that's somewhat harder to read. However that does preserve the exact value of the exit status.
step 1 || { echo >&2 "step 1 failed with code: $?"; exit 2; }
Note, I changed the &&
to a semicolon, since I assume you want to exit even if the error message fails (and output those errors on stderr for good practice).
For the if
variant to preserve the exit status, you'd need to add your code to the else
part:
if step 1; then
: OK, do nothing
else
echo >&2 "step 1 failed with code: $?"
exit 2
fi
(that also makes it compatible with the Bourne shell that didn't have the !
keyword).
As or why the commands group like the do, the standard says:
An AND-OR list is a sequence of one or more pipelines separated by the operators "&&"
and "||"
.
The operators "&&"
and "||"
shall have equal precedence and shall be evaluated with left associativity.
Which means that something like somecmd || echo && exit
acts as if somecmd
and echo
were grouped together first, i.e. { somecmd || echo; } && exit
and not somecmd || { echo && exit; }
.
Best Answer
You could kill the original shell (
kill $$
) before callingexit
, and that'd probably work. But:Instead, you could use one of the several ways to pass back a value in the Bash FAQ. Most of them aren't so great, unfortunately. You may just be stuck checking for errors after each function call (
-e
has a lot of problems). Either that, or switch to Perl.