til

Today I Learned: collection of notes, tips and tricks and stuff I learn from day to day working with computers and technology as an open source contributor and product manager

View project on GitHub

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”

References