[4 Methods] How to Check Exit Code in Bash?

Checking the exit code in Bash is a vital task to determine the success or failure of scripts. It leverages the successful handling of errors along with seamless process control. Therefore, this article provides an in-depth analysis of 4 methods of how to check exit code in Bash. It mentions different command and conditional statement-based methods to check exit codes in Bash to determine if the script ran successfully or encountered errors.

What is a Bash Exit Code?

Bash Exit code is an integer value from 0-255 that indicates the success or failure of a command or Bash script. The executed command or script returns such code to denote whether it executes successfully or encounters any error condition. For example, exit code 0 typically means success while any non-zero code denotes failure.

To find exit codes in Bash, use the following code in the terminal:

echo $?

This returns the exit status of the last executed command or recently executed process.

4 Methods to Check Exit Codes in Bash

This section provides an extensive guide of 4 methods of how to check exit codes in Bash. It mentions the if statement, the test command, and the case statement to check exit codes in Bash and determine if the script ran successfully or encountered errors.

1. Using If Statement and Special Variable $?

Using the if statement with $? is an effective yet straightforward way to check exit codes in Bash. The $? is a special Bash variable that holds the exit code of the last executed command or process. So, checking codes with the if statement using the syntax if [ $? -eq 0 ]  determines whether the script has run successfully or not.

Here’s an example of checking the exit code in Bash using an if statement with the special variable $?:

#!/bin/bash
#the command to be executed 
mv
# if conditional to test the exit codes in Bash
if [ $? -eq 0 ]; then
    echo "Command Execution succeeded"
else
    echo "Command Execution failed"
fi
EXPLANATION

First, the above Bash script attempts to execute the mv command without any arguments which will result in an error. Then the if statement with the condition [ $? -eq 0 ] checks if the exit code of the preceding command is zero using the -eq operator and finds if the script is successful or not. Since, the code will be nonzero, in this case, denoting error condition, the script will print the line “Command Execution failed”  from the else block using the echo command.

bash check exit code using if and $?
Note: In addition, a modified syntax  if (( $? == 0 )) is also a useful tool for checking exit code in Bash. The comparison operator ==, used here, checks if the value of $? (exit code) equals zero.

2. Using If Statement with Command Execution

Apart from using the if statement with conditions, another powerful way of checking exit codes in Bash is to use commands with the “if” statement directly. The syntax is as follows:

if <command>; then
    # code to run if exit status is zero
else 
    # code to run if exit status is nonzero
fi 

Here, first, the <command> executes, and if its exit status is zero, then the condition of if evaluates to true and executes the if block. Otherwise, the else block executes since the if condition evaluates to false denoting the failure of <command>.

Now look at the example below to check the exit code in Bash using the if statement with command execution:

#!/bin/bash

if pwd; then
    echo "Command succeeded"
else
    echo "Command failed"
fi
EXPLANATION

The script above runs the pwd command and it will succeed if the condition becomes true. Thus, the message of the if block executes to denote the success of the script’s execution. Otherwise, if fails, the else block executes.

command execution with if checks exit codes

So, you see that the pwd command runs smoothly to print the current working directory which, results in the printing of the message “Command succeeded”.

3. Using “test” command

The test command is often used to evaluate expressions in Bash. For example, the test $var1 -eq $var2 evaluates if var1 and var2 are equal. So, in the context of checking exit codes, the “test” command with an if statement evaluates the expression $? -eq 0 of the syntax if test $? -eq 0. Then it acts accordingly by discerning the condition of the if statement (either true or false).

Here’s how to check the Bash exit code using the test command:

#!/bin/bash

ls /nonexistent_directory

if test $? -eq 0; then
    echo "Command succeeded"
else
    echo "Command failed"
fi
EXPLANATION

Here, the above Bash script runs the ls command to list the contents of the  nonexistent_directory which will fail and return a nonzero exit code. So,  after checking the exit code using if test $? -eq 0,  the if condition evaluates to false. Thus, the script prints the message of the else block.

test command checking codes for exit in Bash

The script checks the exit code and outputs the error message “Command failed” due to a listing of the directory that does not exist.

3.1 Using “test” Command with Logical Operators

Combined with logical operators, the test command can be a more effective and powerful tool for checking the Bash exit codes. Look at the example below that uses the  OR (||), and the AND (&&) logical operators in conjunction with the test command to check the exit code and decide the success or failure of scripts:

#!/bin/bash
#the command to run
ls /nonexistent_directory
#check exit code with test and logical operators
test $? -eq 0 && echo "Command succeeded" || echo "Command failed"
EXPLANATION

The script above first runs the ls command on a directory named nonexistent_directory and then uses the test $? -eq 0 command to check if the exit code is zero. If yes, the && (AND) operator ensures to print “Command succeeded”. Otherwise, the || (OR) operator ensures displaying “Command failed” on the screen using the echo command.

test command with logical operatorSince the given command runs with an error (returns non-zero exit status), the echo command prints “Command failed”.

4. Using the “case” Statement

The case statement is another handy tool for checking Bash exit codes. It is a conditional structure that looks for patterns such as numeric values (exit code values in this case) and executes different code blocks based on the final output.

Look at the below example to check exit codes in Bash using the case statement:

#!/bin/bash
# Execute a command that may pass or fail
non_existent_command
# Check the exit status using a case statement
case $? in 
    0)
        echo "Command executed successfully."
        ;;
    *)
        echo "Command failed with exit status: $?"
        ;;
esac
EXPLANATION

Here, the script attempts to run a non_existent_command (which is expected to fail) and then the case statement checks the value of the special variable $? (holds the exit code value). Since the command does not exist, the script prints the failure message with the appropriate exit code.

the case statement checks exit codes

The case statement checks that the script case1.sh has failed with exit code 127 since the non_existent_command doesn’t exist.

Conclusion

This article provides an extensive discussion of 4 methods for how to check the exit code in Bash. It has mentioned the use of if statements with several effective approaches (special variable $?, comparison operator ==, direct command execution) for checking Bash exit codes to determine the success or failure of scripts. In addition, it has shed light on the test command and case statement for a successful checking of Bash exit codes. It has discussed how logical operators and comparison operators can be effective in such a checking process. After mastering this essential technique, it would be easy to determine if there’s any error in a script’s execution and proceed appropriately based on the exit status.

People Also Ask

Can I check the exit code of a command in Bash?

Yes, you can check the exit code of a command in Bash. To check the exit code of a command, use the special variable $? with the echo command to display the value in the terminal for successful checking. By default, the variable “$?” holds the value of the exit code of the last executed command. For instance, after running the command whoami, executing echo $? command will print 0 on the screen to denote that the command has been executed successfully.

What does a non-zero exit code mean in Bash?

A nonzero exit code in Bash typically means that the recently executed command or script has encountered an error condition or has failed to execute successfully. For instance, exit code 2 can signify various errors such as an attempt to access a file or directory that is not present in the system. These non-zero exit codes leverage the effective detection and handling of errors and graceful control of the flow of action.

How can I check exit codes in Bash scripts?

To check exit codes in Bash scripts, you can use the if statement to check if the exit code equals zero or not. This lets you determine whether the script executes successfully or has encountered an error. For example, after running the command pwd within a script, you can use the syntax if [ $? -eq 0 ] to check if the exit code stored by the special variable $? is zero to determine the possible flow of action based on the code.

Why do we need to test the exit codes of a script or command in Bash?

Because the process of testing exit codes of a script or command in Bash is crucial in error handling and debugging to ensure the robustness of process execution. By testing exit codes, users easily determine the success or failure of a command or script. This allows them to determine possible actions based on the exit codes for achieving a smooth control flow of processes such as scripts.

How to check the exit status in the terminal?

To check the exit status in the terminal, run the command echo $? after the execution of the command or script you want the status of. The $? is a special variable that stores the exit code and the echo command displays the value in the terminal. For instance, after running the command date, executing the echo $? will print 0 if date succeeds. Otherwise, it will print a nonzero code to indicate failure.

Do the terms “Bash check exit code” and “Bash test exit code” refer to the same meaning in Bash scripts?

Yes. “Bash check exit code” and “Bash test exit code” essentially refer to the same meaning. Both terms involve verifying the exit codes of the last executed script to determine its success or failure. So, whether it’s checking or testing Bash exit codes, the objective is to examine exit codes for error handling and process control in Bash scripts.

Is it possible to check the success of a Bash script?

Yes, it is possible to check the success of a Bash script. So, to check the success of a Bash script, just examine the status code of the script using the special variable $? (It holds the exit status of the last executed script or command). For instance, use the code echo $? to print the exit code in the terminal. So, if the exit status is 0, it denotes that the script has run successfully without encountering errors. This is how you can check the success of a Bash script.

How to return exit codes in Bash scripts?

To return exit codes in Bash scripts, use the command exit followed by the status code you intend to return based on your flow of action in the script. For instance, using the exit 0 command will return the exit code 0 after the successful execution of the script. This effectively communicates the success or failure of scripts, enabling error handling and process control.

Related Articles


<< Go Back to Exit Codes in Bash | Bash Process and Signal Handling | Bash Scripting Tutorial

Rate this post
LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now
icon linux
Md Masrur Ul Alam

Assalamu Alaikum, I’m Md Masrur Ul Alam, currently working as a Linux OS Content Developer Executive at SOFTEKO. I completed my Bachelor's degree in Electronics and Communication Engineering (ECE)from Khulna University of Engineering & Technology (KUET). With an inquisitive mind, I have always had a keen eye for Science and Technolgy based research and education. I strongly hope this entity leverages the success of my effort in developing engaging yet seasoned content on Linux and contributing to the wealth of technical knowledge. Read Full Bio

Leave a Comment