An exit code, or sometimes known as a return code, is the code returned to a parent process by an executable. On POSIX systems the standard exit code is
0 for success and any number from
255 for anything else.
Exit codes can be interpreted by machine scripts to adapt in the event of successes of failures. If exit codes are not set the exit code will be the exit code of the last run command.
To get the exit code of a command type
echo $? at the command prompt. In the following example a file is printed to the terminal using the cat command.
cat file.txt hello world echo $? 0
The command was successful. The file exists and there are no errors in reading the file or writing it to the terminal. The exit code is therefore
In the following example the file does not exist.
cat doesnotexist.txt cat: doesnotexist.txt: No such file or directory echo $? 1
The exit code is
1 as the operation was not successful.
To use exit codes in scripts an
if statement can be used to see if an operation was successful.
#!/bin/bash cat file.txt if [ $? -eq 0 ] then echo "The script ran ok" exit 0 else echo "The script failed" >&2 exit 1 fi
If the command was successful the exit code will be
0 and ‘The script ran ok’ will be printed to the terminal.
To set an exit code in a script use
exit 0 where
0 is the number you want to return. In the following example a shell script exits with a
1. This file is saved as
#!/bin/bash exit 1
Executing this script shows that the exit code is correctly set.
bash exit.sh echo $? 1
The Linux Documentation Project has a list of reserved codes that also offers advice on what code to use for specific scenarios. These are the standard error codes in Linux or UNIX.
1- Catchall for general errors
2- Misuse of shell builtins (according to Bash documentation)
126- Command invoked cannot execute
127- “command not found”
128- Invalid argument to exit
128+n- Fatal error signal “n”
130- Script terminated by Control-C
255\*- Exit status out of range
Sometimes there may be a requirement to suppress an exit status. It may be that a command is being run within another script and that anything other than a
0 status is undesirable.
In the following example a file is printed to the terminal using cat. This file does not exist so will cause an exit status of
To suppress the error message any output to standard error is sent to
If the cat command fails an
OR operation can be used to provide a fallback -
cat file.txt || exit 0. In this case an exit code of
0 is returned even if there is an error.
Combining both the suppression of error output and the
OR operation the following script returns a status code of
0 with no output even though the file does not exist.
#!/bin/bash cat 'doesnotexist.txt' 2>/dev/null || exit 0
Have an update or suggestion for this article? You can edit it here and send me a pull request.