Linux Bash Exit Codes Explained
What is an Exit Codes in Linux Bash
An exit code, or sometimes known as a return code, is the code returned to a parent process by an executable.
Every script, command, or binary exits with a return code.
Just type $? and press enter and you will see the exit code of the previous command.
Exit code “0” or zero denotes success of the command.
Bash has some reserved exit codes for different situations. So, you should avoid using reserved exit codes as it will make debugging harder because of conflicting results. Return codes are numeric and are limited to being between 0-255. 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.
Below table details the reserved exit codes:
Exit Code Number | Description | 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 |
Example 1: Exit code for “success” and illegal command
$ date
Thu May 13 09:52:04 AEST 2021
$ echo $?
0
$ dater
-bash: dater: command not found
$ $?
-bash: 127: command not found