Bash – how to find last command exit status code

When writing bash scripts or running something on command line, last command exit code status is stored in environment variable $?. It can also be used to get exit code of subshell command $(). Here is example bash code showing how you can use it.

ls /etc/passwd_non_existing > /dev/null 2>&1 
echo "exit code: $?"
ls /etc/passwd
echo "exit code: $?"
somevar=$(ls /etc/passwd_non_existing)
echo "exit code: $?"
exit code: 2
/etc/passwd
exit code: 0
exit code: 2
Env: GNU bash, version 4.3.11
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments