What are Bash Exit Codes in Linux

What is an exit code

Every script, command, or binary exits with a return code. You can see this value in the special variable $?. Return codes are numeric and are limited to being between 0-255 because an unsigned 8-bit integer is used. If you use a value of -1, it will return 255. Each execution terminates with an exit code, whether successful or not, with an error message or silently. For example:

$ date ; echo $?
Sat Jan 18 08:06:07 IST 2020
0

As you can see, the exit code is 0 because the command was executed without issues. Now, let’s try this:

$ wrngcmd ; echo $?
-bash: wrngcmd: command not found
127

It is a command not found as we just typed a meaningless bunch of characters.

Reserved Bash Exit Codes

So similar to the exit code “0” which denotes success of the command, bash has some reserved exit codes for different situations. So ideally if you are using exit command in a script and need to specify an exit code, do not use these reserved exit codes as they may create conflicting results.

Exit Code Number Meaning Example Comments
1 Catchall for general errors let “var1 = 1/0” Miscellaneous errors, such as “divide by zero” and other impermissible operations
2 Misuse of shell builtins empty_function() {} Missing keyword or command
126 Command invoked cannot execute /dev/null Permission problem or command is not an executable
127 “command not found” illegal_command Possible problem with $PATH or a typo
128 Invalid argument to exit exit 3.14159 exit takes only integer args in the range 0 – 255 (see first footnote)
128 +n Fatal error signal “n” kill -9 $PPID of script $? returns 137 (128 + 9)
130 Script terminated by Control-C Ctrl-C Control-C is fatal error signal 2, (130 = 128 + 2, see above)
255* Exit status out of range exit -1 exit takes only integer args in the range 0 – 255

Lets understand the exit code “128 +n” with an example. Run the never-ending loop as shown below:

#!/bin/bash    
while true; do    
echo ${$}    
done

If you run this script it will print the same PID indefinitely untill you kill it or do a “CTRL+C”. Let try doing a “CTRL+C” and see what is the exit code.

# sh test.sh
....
2582
2582
2582
2582
2582
2582
^C
geeklab$ echo $?
130

As you can see the exit code is “128+2” i.e. 130. Similarly if we kill the script using “kill -9” the exit code should be “128+9” i.e. 137. Lets see an example of that too:

# sh test.sh
....
2582
2582
2582
...
# kill -9 [pid_of_script]
....
2602
2602
Killed: 9
geeklab$ echo $?
137
Related Post