What are exit codes in Linux?

Sachithra_Manamperi
3 min readOct 28, 2022

An exit code in Linux represents the result of the execution of a command or script.

It has a scale ranging 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 implies an unexpected outcome.

As soon as the command or script has done executing, we can use $? to get the exit code of the process.

The Exit codes of any command are stored in a special built-in variable called $?. When a command is successful, a zero is returned. when a command fails it returns a value greater than zero.

The $? variable is updated immediately after a command is executed. so the value of this variable is only reliable right after running a command

Note: Exit codes are also known as return codes.

For successful commands, it returns a 0

It will return a non-zero value when a command is not valid

Here’s an example:

Explanation

In the above example:

  1. The command echo “Hello There!” was executed, and the result was printed on the line after. The command echo $? was then executed, and when it returned 0 as output, it was successful.
  2. When we used the command cat demofile.txt, it failed with the following error: There is no such file or directory, and a failure is indicated by the return code of 1.

Reserved exit codes

There are several reserved exit codes in Linux that have unique meanings. 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

In a shell script, exit codes are typically used to check the status and take appropriate action.

To test for a common use case and determine whether the command executes successfully, we run several commands in a shell script.

Let’s create a shell script file call check.sh

# run_some_command

if [ $? -eq 0 ]; then

echo OK

else

echo FAIL

fi

Explanation

The above code determines whether the return code is equal to 0. If so, we can echo “OK.” If not, we iterate FAIL.

Best Practice: Always return appropriate exit codes in your script because It will help to integrate with other scripts

--

--

Sachithra_Manamperi

Undergraduate | Software Engineering | Dharmaraja College Kandy | Sri Lankan