What are exit codes in Linux?
Overview
In Linux, an exit code indicates the response from the command or a script after execution. It ranges from 0 to 255. The exit codes help us determine whether a process ran:
- Successfully.
- Failed due to an error.
- Or another state that gives us an indication of an unexpected result.
Note: Exit codes are also known as return codes.
We can get the process's exit code once the command or script execution is complete using $?.
Example
Here's an example:
root@educative:/# echo "Hello There!"Hello There!root@educative:/# echo $?0root@educative:/# cat demofile.txtcat: demofile.txt: No such file or directoryroot@educative:/# echo $?1
Note: The terminal is attached to the end of the shot. Please copy the commands from above and paste them into the terminal to try them.
Explanation
In the above example:
- We ran the command
echo “Hello There!”and it printedHello There!on the following line. Then we ran the commandecho $?and it provided output as0, which indicates that the command ran successfully. - We ran the command
cat demofile.txt, and it gave us an errorcat: demofile.txt: No such file or directory, and the return code is1, indicating a failure.
Reserved exit codes
Linux has some reserved exit codes with a special meaning. Here's the list of exit codes:
1: Catchall for general errors2: Misuse of shell built-ins (according to Bash documentation)126: Command invoked cannot execute127: “Command not found.”128: Invalid argument to exit128+n: Fatal error signal “n”130: Script terminated by Control-C255\*: Exit status out of rangeExit codes are usually used in the shell script to check the status and take actions accordingly. We run multiple commands in a shell script to check for an everyday use case and see if the command runs successfully. Here's an example:
# some_commandif [ $? -eq 0 ]; thenecho OKelseecho FAILfi
Explanation
In the code above, we check if the return code is equal to 0. If it is, then we echo OK. Otherwise, we echo FAIL.