Bash How to Get Exit Status

Bash How to Get Exit Status

The answer is in this special shell variable “$?”. In this variable is saved exit status of the last command that ended in the background.

In the next example “paranormal_directory” doesn’t exists, at all. It is a paranormal directory 🙂 In this example, $? variable will be 2, because command ls fails:

ls paranormal_directory 1>/dev/null 2>&1
echo $?

Output: 2

Listing the home folder is always safe. Executing ls without any parameter lists home folder of the current user. In this example, ls will succeed, so variable “$?” will be 0:

ls 1>/dev/null 2>&1
echo $?

Output: 0

But be careful, if you read this variable two times (echo $?). In the next example, “echo $?” (on line 3) will show you the output of the first echo command (on line 2):

ls paranormal_directory 1>/dev/null 2>&1
echo $?
echo $?

Output: 2 0

What happens if you don’t specify the exit code in the script? When the exit code is not specified with the exit command, the exit code of the script will be the exit code of the last executed command.

Leave a Comment