An Overview of Linux Exit Codes

[article]
Summary:

Understanding exit codes is essential for detecting errors, automating tasks, debugging issues, and facilitating inter-process communication. By mastering the key exit codes and their meanings, Linux users can effectively manage and troubleshoot their command execution and shell scripting.

What Are Exit Codes on Linux?

An exit code, also known as an exit status, in Linux is a numerical value returned by a command or program to indicate its execution result. This code provides information on whether the command completed successfully or encountered errors. A common use for exit codes in modern infrastructure is container exit codes, which provide insight into errors in containerized applications.

In Linux, the exit codes range from 0 to 255, with 0 representing success, and 1-255 indicating various failure conditions. The $? variable is a special shell variable that stores the exit status of the most recently executed command or script. By examining the value of this variable, you can determine the success or failure of a command or script and take appropriate action.

Failure codes, as mentioned, are within the 1-255 range, with each number representing a specific type of error. This range allows for a wide variety of error codes, enabling granular identification of issues that may arise during the execution of a command or program.

Why Are Exit Codes Important?

Exit codes are important for several reasons, particularly in the context of scripting, automation, and system administration. They provide a standardized way to communicate the success or failure of a command or program, enabling better error handling, control flow, and feedback. Here are some key reasons why exit codes are essential:

  • Error handling: Exit codes allow scripts and automation tools to detect errors or abnormal termination of commands, making it possible to handle different error conditions gracefully. This helps to maintain the stability and reliability of your scripts, even when unexpected issues arise. For example, exit codes can help troubleshoot the problem on a server when a 5xx server error occurs.
  • Control flow: By checking the exit codes of commands, you can control the flow of execution in your scripts based on the success or failure of previous commands. This enables you to create more robust scripts that can adapt to different situations and respond appropriately.
  • Feedback: Exit codes provide feedback to the user or calling process about the result of a command or program. This can be especially useful in automated systems, where exit codes can be logged or monitored to detect potential issues early.
  • Integration: When developing custom tools, programs, or scripts, using standardized exit codes ensures better integration and interoperability with other tools, scripts, or systems that rely on exit codes for decision-making and error handling.
  • Debugging: Exit codes can help you identify issues during the development and debugging process. By checking the exit codes of commands or functions, you can pinpoint problems and fix them more efficiently.

List of Key Exit Codes in Linux

In Linux and other Unix-like operating systems, certain exit codes are widely recognized and have conventional meanings. While exit codes are often specific to individual commands or programs, some of the most common exit codes you may encounter include:

  • 0: Success—Indicates that the command or program executed successfully without any errors.
  • 1: General Error—A catch-all exit code for a variety of general errors. Often used when the command or program encounters an error, but no specific exit code is available for the situation.
  • 2: Misuse of shell built-ins—Indicates incorrect usage of shell built-in commands or misuse of shell syntax.
  • 126: Command cannot execute—The command was found, but it could not be executed, possibly due to insufficient permissions or other issues.
  • 127: Command not found—The command was not found in the system's PATH, indicating that either the command does not exist or the PATH variable is incorrectly set.
  • 128: Invalid exit argument—Returned when a script exits with an invalid argument. This usually indicates an error in the script itself.
  • 128 + N: Fatal error signal N—Indicates that the command or program was terminated by a fatal error signal. For example, an exit code of 137 (128 + 9) means that the command was terminated by a SIGKILL signal.
  • 130: Script terminated by Control-C—Indicates that the command or script was terminated by the user using Control-C (SIGINT signal).
  • 255: Exit status out of range—Returned when the exit status is outside the valid range (0 to 254).

These are just a few of the key exit codes you may encounter in Linux. Keep in mind that the specific meanings of exit codes can vary between commands and programs, so it's essential to consult the documentation for the commands you're using to understand the exit codes and their meanings.

Using Exit Codes in Linux

Below is an overview of how to use exit codes in various contexts.

Using Exit Codes in Scripts

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 was successful"
  exit 0
else
  echo "The script did not run" >&2
  exit 1
Fi

Save the above script in a file named run.sh. You will need to provide appropriate permission by executing this command: sudo chmod +x run.sh

First, try running without file.txt, and then create file.txt in the current directory and execute the run.sh script again.

If the script ran successfully, it should have an exit code of 0 and display the message “The script was successful,” while any other exit code will be accompanied by a message in the terminal saying “The script did not run.”

Setting Exit Codes

You can set exit codes in a Linux script using exit 0, with 0 representing the response you want. Here is an example of a shell script that exits with a code of 1 and saves the file as exit.sh.

#!/bin/bash

exit 1

When you execute this script, you will see that the exit code has been set correctly.

bash exit.sh
echo $?

The output should be an exit code of 1.

Suppress an Exit Status

In some cases, you might want to suppress the exit status if you are running the command alongside other scripts. For example, you can print a file to the terminal using the cat utility—if the file doesn’t exist, it will result in an exit code of 1.

You can suppress this error message by sending the output to a standard error to /dev/null with 2>/dev/null. It’s possible to use an OR operation as a fallback when a cat command fails:

cat file.txt || exit 0

Thus, Linux will return an exit 0 code regardless of whether there was an error. If you combine the error output suppression with this OR operation, the resulting script will display an exit status of 0 output when the file doesn’t exist.

#!/bin/bash

cat 'doesnotexist.txt' 2>/dev/null || exit 0

Store the above commands in a file named err.sh file. Note, there will be no error displayed as we are pushing error messages to 2>/dev/null

Conclusion

This guide has provided a comprehensive overview of the importance, usage, and key exit codes in the Linux environment. Understanding exit codes is essential for detecting errors, automating tasks, debugging issues, and facilitating inter-process communication. By mastering the key exit codes and their meanings, Linux users can effectively manage and troubleshoot their command execution and shell scripting.

This knowledge will empower you to create more robust and error-resilient scripts, ensuring the smooth operation of their Linux systems. As a result, you will be better equipped to handle any challenges you may encounter and fully harness the power and flexibility that Linux offers.

About the author

AgileConnection is a TechWell community.

Through conferences, training, consulting, and online resources, TechWell helps you develop and deliver great software every day.