Course contentsShow
← Linux
Lesson 302 of 1,8193. The Filesystem Hierarchy and POSIX StandardsFree lesson

Standard Error Reporting and Exit Status

Implement robust error handling by interpreting standardized exit status codes.

In this lesson, you will learn how to interpret standardized exit status codes to determine whether a process succeeded or failed.

When a process finishes its execution in Linux, it doesn’t just vanish; it leaves behind a small numeric value known as an exit status (or return code). This is the primary way a process "reports" its success or failure to the shell or a parent process.

The Logic of Exit Status

According to POSIX standards, an exit status of 0 is interpreted as "success." Any non-zero value (typically ranging from 1 to 255) indicates that an error occurred. These numbers act as a shorthand for the process to tell the operating system what went wrong without needing to write a complex error message to the screen.

You can inspect the result of the last executed command by checking the special shell variable $?.

Practical Example

If you try to list a file that doesn't exist, the ls command encounters an error. We can capture that error immediately:

# Attempt to list a non-existent file
ls nonexistent_file.txt

# Check the exit status of the previous command
echo $?
# Output: 2

In this case, the ls command returned 2, which is the standard code for "misuse of shell built-ins" or "file not found" depending on the implementation. If the command had succeeded, $? would have been 0.

Standard Error Reporting

While the exit status is a simple number, the process simultaneously sends descriptive error messages to the Standard Error (stderr) stream. While the exit status tells your script that something went wrong (the "what"), the stderr stream provides the human-readable context (the "why").

By combining these, you can write robust scripts that check the exit status before proceeding:

./my_script.sh
if [ $? -ne 0 ]; then
    echo "The process failed. Check the logs above."
fi

By relying on the 0 for success and non-zero for failure rule, you can create automation that reacts intelligently to the health of your filesystem operations and process execution.

Key Takeaway: An exit status of 0 always signifies success, while any non-zero value acts as a standardized flag indicating that an error occurred during execution.