How to get last return value
If you want to get the last return value in bash
, do the following:
$ echo $?
For doing something a tad more elegant in scripts etc. The following suggestion from StackOverflow looks pretty nifty:
EXITCODE=$?
test $EXITCODE -eq 0 \
&& echo "something good happened" \
|| echo "something bad happened";
exit $EXITCODE
However echo
is not recommended, but printf
is:
EXITCODE=0
test $EXITCODE -eq 0 \
&& printf "Success: %d\n", $EXITCODE \
|| printf "Error: %d\n", $EXITCODE;
exit $EXITCODE
See also: “Write Safe Shell Scripts”