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:

  1. Successfully.
  2. Failed due to an error.
  3. 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 $?
0
root@educative:/# cat demofile.txt
cat: demofile.txt: No such file or directory
root@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:

  1. We ran the command echo “Hello There!” and it printed Hello There! on the following line. Then we ran the command echo $? and it provided output as 0, which indicates that the command ran successfully.
  2. We ran the command cat demofile.txt, and it gave us an error cat: demofile.txt: No such file or directory, and the return code is 1, 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 errors
  • 2: Misuse of shell built-ins (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
  • Exit 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_command
    if [ $? -eq 0 ]; then
    echo OK
    else
    echo FAIL
    fi

    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.

    Terminal 1
    Terminal
    Loading...