Skip to content

Click on each book below to review & buy on Amazon.

As an Amazon Associate, I earn from qualifying purchases.


LPI Linux Essentials Exam 010-160 - Topic 3.3 - Exit Codes in Shell Scripting

Exit codes in Linux serve as a means for commands and scripts to communicate the outcome of their execution. These codes are essentially integers that provide insight into the execution of a command, indicating whether it was successful or encountered an error, and if so, what kind of error. When a script or command in Linux concludes, it returns an exit code, also known as a return code or status code, to the shell. This code is a vital part of error handling, influencing the flow of scripts and aiding in process automation. Grasping the significance of these codes is therefore a fundamental aspect of scripting and system administration.

Detailed Understanding of Exit Codes

In the Unix and Linux environments, exit codes are within the range of 0 to 255. The following are some of the typical codes you may come across:

Exit Code Meaning
0 The command or script executed successfully without any errors.
1 General error; the default code when the exact nature of the problem is unspecified.
2 Misuse of shell commands, such as incorrect number of arguments or invalid options.
126 Command is found but not executable, possibly due to permission issues or incorrect file types.
127 Command could not be found, suggesting a typo or a problem with the user's PATH.
128 Invalid exit argument, usually when an exit status is out of the allowable range.
130 Script terminated by the user, such as when pressing Ctrl+C.
255 Exit status out of range or unknown error, a catch-all for errors that don't fit other categories.

These codes, while somewhat standardized, can be specific to the command that was executed. For accurate interpretations, it is best to consult the documentation for the particular command to understand its exit statuses.

Incorporating Exit Codes in Scripts with the exit Command

The exit command in Linux terminates a script or a shell and returns a value to the parent process. This value is the exit code, which can be explicitly set to convey a status back to the script’s caller.

#!/bin/bash

# Exit the script with a custom exit code
function my_function {
  # If an error condition is met, exit with a specific code
  if [ condition ]; then
    echo "An error occurred"
    exit 22  # This is a custom exit code to indicate a specific failure
  fi
}

# Call the function and then check the exit code
my_function
echo "The function exited with status $?"

Here, exit 22 is used to return a custom exit code, which can be subsequently checked with $?.

Employing the $? Variable for Immediate Status Checks

The special variable $? captures the exit status of the most recently executed foreground command. It is an automatic feature of the shell that is assigned immediately after a command exits.

  • A 0 stored in $? confirms that the command before it was successful.
  • A non-zero value in $? indicates an error, with the number signifying the nature of the issue.

Practical Examples of Exit Code Usage

To fully illustrate the use of $?, consider a scenario where you execute a command to list contents of a directory that does not exist:

#!/bin/bash

# Attempt to list contents of a non-existent directory
ls /nonexistent/directory

# Check if the command was successful
if [ $? -eq 0 ]; then
    echo "The directory was listed successfully."
else
    echo "An error occurred while trying to list the directory."
fi

In this script, if ls cannot find the directory, it exits with a code that is not zero, triggering the error message.

Moving on to a case of conditional action based on the result of a search command:

#!/bin/bash

# Search for a specific string in a file
grep "desired_string" example.txt

# React to the absence of the desired string
if [ $? -ne 0 ]; then
    echo "The string was not found in the file."
fi

If grep does not find the string, it exits with a code other than zero, and the script informs the user accordingly.

Another common use case is storing the exit status for later use, which is particularly useful when multiple commands run sequentially and you need to check the status at a later point:

#!/bin/bash

# Create a backup archive of a directory
tar -czf backup.tar.gz /path/to/important_data
# Store the exit status immediately after the command
backup_status=$?

# Use the stored status to inform the user of the result
if [ $backup_status -eq 0 ]; then
    echo "Backup was created successfully."
else
    echo "The backup process encountered an error with status code $backup_status."
fi

In this script, the exit code from tar is stored in a variable named backup_status. The script checks the value of backup_status and communicates the outcome of the backup operation to the user.

The $? variable is a powerful tool for creating responsive scripts that can handle errors gracefully and make decisions based on the success or failure of commands. It is a simple yet effective means of enhancing the robustness of shell scripts in Linux.


Support DTV Linux

Click on each book below to review & buy on Amazon. As an Amazon Associate, I earn from qualifying purchases.

NordVPN ®: Elevate your online privacy and security. Grab our Special Offer to safeguard your data on public Wi-Fi and secure your devices. I may earn a commission on purchases made through this link.