Log exit code of command, similar to time command

exitexit-status

using

time sleep 1

yields:

$ time sleep 1

real    0m1.005s
user    0m0.001s
sys     0m0.001s

is there a command I can use to print the exit code of sleep or whatever command I want to run?

Something likes:

$ log-exit-code sleep 1

perhaps this sufficient?

sleep 1 && echo "$?"

Best Answer

In my testing so far this has worked:

command && echo "$?" || echo "$?"

Just tells it to echo the exit code if it succeeds or if it fails.

As Sato pointed out below this is essentially the same as:

command; echo "$?"

One thing that could make the and/or command worthwhile is something like:

command && echo "Success! Exit Code: $?" || echo "Failure! Exit Code: $?"

If you need your script to act on the exit code as is Olivier's concern, it is a non issue. Your script could look something like:

command
case "$?" in; 
    0) echo "Command exited with: 0"
       <command if good>
       ;;
    1) echo "Command exited with: 1"
        <command if bad>
        ;;
    255) echo "Command exited with: 255"  # for ssh maybe?
         <command if 255>
         ;;
    *) echo "Command exited with: >2"
        <command for other exit code>
        ;;
esac
Related Question