How to check if a command succeeded?
The return value is stored in $?
. 0 indicates success, others indicates error.
some_command
if [ $? -eq 0 ]; then
echo OK
else
echo FAIL
fi
Like any other textual value, you can store it in a variable for future comparison:
some_command
retval=$?
do_something $retval
if [ $retval -ne 0 ]; then
echo "Return code was not zero but $retval"
fi
For possible comparison operators, see man test
.
If you only need to know if the command succeeded or failed, don't bother testing $?
, just test the command directly. E.g.:
if some_command; then
printf 'some_command succeeded\n'
else
printf 'some_command failed\n'
fi
And assigning the output to a variable doesn't change the return value (well, unless it behaves differently when stdout isn't a terminal of course).
if output=$(some_command); then
printf 'some_command succeded, the output was «%s»\n' "$output"
fi
http://mywiki.wooledge.org/BashGuide/TestsAndConditionals explains if
in more detail.
command && echo OK || echo Failed