Check Exit Code Equal to “0” or Not With Bash Case Statement 

In Bash, the exit code “not equal to 0” represents the failure of a command. If the exit status value is “equal to 0”, the command will be successful. Now, to handle errors, it is crucial to check the exit status of a command. Checking the exit code using case statement allows you to produce more readable and handy scripts. In this article, I’ll show you how to determine whether a command passes or fails based on the exit value equal to zero or non-zero within the case statement.

What is Exit Code in Bash?

The exit code in bash is a string value indicating whether the command is successful or not. Basically, when you execute a command in bash, bash sets the exit status to either 0 or non-zero. If the exit code value is 0, then the command succeeded. If the value is non-zero, then the command failed. The value of exit status can be between 0 and 255, the greater value indicates more severe errors.

How Does Exit Code Work Within Bash Case Statement?

Using the case conditional construct, you can check the exit status of any command. After the execution of any command, first, the value of the exit status will be stored inside the $? variable. And, based on the variable value, if the exit status is equal to 0, the case statement executes the code after the 0) pattern. But if the exit status is not equal to 0, the statement executes the code after *) pattern. Here’s how:

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

After running the command, if the exit code is 0, the “Command executed successfully.” will be displayed, otherwise, it will print another code block after *).

3 Examples to Check If Exit Code Equal to 0 or Not Using Bash Case Statement

Implementing the case statement to check whether the exit status is equal to “0” or not verifies the success or failure of a command. The exit status equal to “0” will prove the success of the command. On the other hand, the command will fail. In this section, I will show you 3 practical examples using different commands, after command execution, I will check their exit status. Based on the exit status, the case statement will execute the corresponding statements. Let’s check these examples:

1. Check Exit Code Equal to “0” or Not for Addition Operation

To check whether the addition result is right or wrong, you can use a case statement to check the exit status of the command. When the exit value is not equal to 0, the addition will be unsuccessful. Follow the script below to see the entire process more clearly:

#!/bin/bash
# Attempt to perform an addition operation
sum=$(echo "5 + 7" | bc) 
# Check the exit status of the sum
case $? in 
    0)
        echo "Addition successful. Result: $result"
        ;;
    *)
        echo "Addition failed."
        ;;
esac
EXPLANATION

Here, the $(echo "5 + 7" | bc) command performs an addition operation, and the bc (basic calculator) command-line calculator evaluates the result and prints it to the standard output. Then $? checks the exit status of the summation result. If the exit status is 0, it indicates that the addition is successful. However, if the exit status is non-zero, it executes “Addition failed.”.

Checking exit code for addition operation using bash case statement

In the picture, you can see that the script executes the statement after 0) because the addition is successful and the result is displayed as 12.

2. Check Exit Code Equal to “0” or Not for Searching Pattern

The grep command can be used to search for a specific pattern in a file. In this example, a specific pattern will be searched, and then the exit status will be checked within a conditional case statement to determine if the pattern is present in the file. Let’s look at the following bash script to see how to search for a pattern:

#!/bin/bash
#Create file.txt which contains “hello world”
echo hello world > file.txt  
#Search for a "hello" pattern in the file.txt
grep "linuxsimply" file.txt
# Check the exit status
case $? in 
    0)
        echo "Pattern found in the file."
        ;;
    *)
        echo "Pattern not found in the file."
        ;;
esac
EXPLANATION

After creating file.txt with the content “hello world”, the script searches for a pattern “hello” from the created file using the grep command. If hello is present in the file.txt, the exit status will be 0. If not, the exit status will be non-zero.

searching a pattern and checking the exit code equal to o or not using bash case statement

As you can see it shows “Pattern not found in the file.” because linuxsimply is not present in the text of file.txt. So, here the bash exit status is not equal to 0.

3. Check Exit Code Equal to “0” or Not for Listing Directory Contents

To make a list of files and directories of a particular folder, the ls Command is used. Therefore, if that particular directory does not exist, the ls command will fail and the exit status will be not equal to 0. In this example, I will check my “Downloads” folder’s contents. Here’s the bash script:

#!/bin/bash
# Run a command and check exit status using a case statement
ls Downloads/ 
case $? in
    0)
        echo "Command succeeded: No errors."
        ;;
    *)
        echo "Command failed: Minor errors."
        ;;
esac
EXPLANATION

If the “Downloads” directory exists on my system, the exit status will be 0 and the output will be a list of contents of that directory. If not, the exit status will be non-zero, and it will execute the block after *).

making a list of directory and checking the exit code using bash case statement

In this image, you can see a list of files and directories in the “Downloads” folder, so, the command ran successfully.

Conclusion

In summary, the exit code equal to “0” or not in case statements is a fundamental requirement for reliable and robust automation of scripts. By checking the exit code, you can handle unexpected errors. In this post, I have provided 3 examples of checking exit status. Please check the examples carefully to understand them well. Good luck!

People Also Ask

What is the purpose of using case statement to check the exit status?

The case statement is one of the most useful constructs in bash. It makes it easy to handle different types of exit status. You can use the case statement to evaluate the exit status of the command and execute certain code blocks according to the conditions given. This makes it easier to keep track of the script and understand it better.

Why is checking for “NOT EQUAL TO 0” important in bash scripting?

It is essential to check for “Not Equal to 0” in the bash script in order to handle the error properly. It allows the scripts to detect and react to failed command executions. Additionally, it allows for the implementation of conditional logic based on various exit statuses.

How can I use the not equal condition in a case statement for multiple exit statuses?

Multiple exit statuses can be handled by extending the case statement. For instance:

case $? in
    0)
        echo "Command executed successfully."
        ;;
    1)
        echo "Command failed: Error 1."
        ;;
    2)
        echo "Command failed: Error 2."
        ;;
    *)
        echo "Unknown error occurred. Check the logs for details."
        ;;
esac

If the exit status is not equal to 0, it can execute different code blocks like the blocks after 1), 2), and *).

How can I log error messages when the exit status is “Not Equal to 0”?

You can implement logging by redirecting the error messages to a log file. For example:

#!/bin/bash
command 2>> error.log        
 # Check the exit status using a case statement
case $? In                                    
    0)
        echo "Command executed successfully."
        ;;
    *)
        echo "Command failed. Check 'error.log' for details."
        ;;
esac

By appending the error of a command to the error.log file, you can check the exit status using a case statement.

Related Articles

<< Go Back to Case Statement in Bash | Bash Conditional Statements | Bash Scripting Tutorial

5/5 - (5 votes)
Mitu Akter Mou

Hello, This is Mitu Akter Mou, currently working as a Linux Content Developer Executive at SOFTEKO for the Linuxsimply project. I hold a bachelor's degree in Biomedical Engineering from Khulna University of Engineering & Technology (KUET). Experiencing new stuff and gathering insights from them seems very happening to me. My goal here is to simplify the life of Linux users by making creative articles, blogs, and video content for all of them. Read Full Bio

Leave a Comment