Every Linux or Unix command executed by the shell script or user, has an exit status. The exit status is an integer number. For the bash shell's purposes, a command which exits with a zero (0) exit status has succeeded. A non-zero (1-255) exit status indicates failure. All of the Bash builtins return exit status of zero if they succeed and a non-zero status on failure.
You can use special shell variable called $?
to get the exit status of the previously executed command.
List of reserved exit codes for bash scripting.
Exit Code Number | Meaning | Description |
---|---|---|
1 | Catchall for general errors | Miscellaneous errors, such as divide by zero and other impermissible operations |
2 | Misuse of shell builtins | Invalid option of bash builtin, trying to access a file or directory that doesn't exist or requires permissions |
126 | Command invoked can't be executed | Permission problem or command is not an executable |
127 | Command not found | |
128 | Invalid argument to exit |
exit takes only integer args in the range 0 - 255 |
128+n | Fatal error signal "n" | In Linux, programs might send one of 31 different standard signals. When a program terminates after receiving one of these signals, it returns an error code equal to 128 + signal-number. |
According to the above table, exit codes 1 - 2, and 126 - 165 have special meanings, and should therefore be avoided for user-specified exit parameters.
Let's simulate the exit codes
General Error: 1
$ echo $((10 / 0))
bash: 10 / 0: division by 0 (error token is "0")
$ echo $?
1
Misuse of Shell Built-in: 2
$ ls nonexistdirectory/
ls: cannot access 'nonexistdirectory/': No such file or directory
$ echo $?
2
Cannot Execute: 126
$ cat nonexecutablescript.sh
#!/bin/bash
echo hello
$ chmod -x nonexecutablescript.sh
$ ./nonexecutablescript.sh
bash: ./nonexecutablescript.sh: Permission denied
$ echo $?
126
Command Not Found: 127
$ execute
bash: execute: command not found
$ echo $?
127
Fatal Error Signal n: 128+n
When we terminate a program by using Ctrl+C, we effectively send it a SIGINT
signal. This signal has a value of 2. Therefore, the program will stop executing and return an exit code with a value 128 + 2 = 130.
$ ^C
$ echo $?
130