Understanding Linux Exit Codes - Success and Error Codes | DevTools

Learn about Linux exit codes, also known as return codes. Understand common exit codes like 0 for success, 1 for general errors, 126 for permissions, 127 for command not found, and 130 for Ctrl+C termination.

Linux Exit Codes Explained

Understanding Linux Exit Codes

In Linux and other Unix-like operating systems, exit codes, also known as return codes, are numerical values that a command or process returns to the operating system upon its completion. These codes provide a simple way to indicate whether the command executed successfully or encountered an error. Understanding these codes is crucial for effective shell scripting and system administration, allowing you to build robust scripts that can react to different execution outcomes.

Common Exit Codes and Their Meanings

While there are many possible exit codes, a few are standardized and frequently encountered:

Exit Code Description
0 Success: Indicates that the command or process completed without any errors. This is the most common and desired exit code.
1 General Error: A catch-all for various types of errors that don't fit into more specific categories. It signifies that something went wrong during execution.
126 Command Invoked Does Not Have Execute Permissions: This error occurs when you try to run a script or command, but the file lacks the necessary execute permissions. You can often fix this by using chmod +x filename.
127 Command Not Found: The shell could not find the command you tried to execute. This usually means the command is not installed, not in your system's PATH, or you've mistyped its name.
130 Command Terminated Using Ctrl+C: This code is returned when a process is terminated by the user pressing Ctrl+C, which sends an interrupt signal (SIGINT).

Interpreting Exit Codes in Scripts

Shell scripts often use exit codes to control program flow. For example, you can check the exit code of a command using the special variable $?. If $? is 0, the previous command was successful. If it's non-zero, an error occurred.

Example Usage in Bash:


#!/bin/bash

ls /nonexistent_directory

if [ $? -eq 0 ]; then
    echo "Directory listing successful."
else
    echo "Error: Directory listing failed. Exit code: $?"
fi
                

Further Resources