Check If Bash Command Fail or Succeed [Exit If Fail]

LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now

Exit status is the performance indicator that incorporates checking if a command fails or succeeds in Bash. Whether you are developing complex scripts or automating tasks, it is essential to know how to check a command’s success or failure as well as how to exit the script if a command fails or error occurs.

The following article will demonstrate 2 methods to check if a command fails or succeeds and 4 methods to exit if a command fails in Bash. Let’s delve into it!

What is an Exit Code in Bash?

The exit code is an integer value (ranging from 0 to 255) returned by a command after a complete execution. It indicates whether a command executed successfully or encountered any errors. Every command executed in Bash returns an exit code or status of either zero (0) or non-zero value (any value greater than 0) where 0 signifies success and any non-zero value indicates failure.

2 Ways to Check If a Command Fails or Succeeds in Bash

In the following section, I’ll explain 2 methods such as using the special variable $? and using && and || operators to examine the exit status and check if a command fails or succeeds in Bash.

1. Checking Exit Status with $? Variable

In Bash, $? is a special variable that stores the exit status of the last executed command. To check if a command succeeds or not, simply verify the exit status of the command using $?.

Here’s a Bash script to check if a command fails or succeeds using the $? special variable:

#!/bin/bash

#Checking for successful execution
ls -l /home/nadiba/Documents
if [ $? -eq 0 ]; then
    echo "Successful execution of ls command"
fi

#Checking for failed execution
mkdir /home/nadiba/distro
if [ $? -ne 0 ]; then
    echo "mkdir command failed"
fi
EXPLANATION

In the script, if [ $? -eq 0 ] checks the exit status of the recently executed ls command. If the exit status equals zero, it means the ls command executed successfully. In the next part, if [ $? -ne 0 ] checks if the exit status of the last executed mkdir command is not equal to zero. If so, it means the command failed.

Checking if a command succeeds or fails using a special variable in Bash

In the above image, the ls command executed successfully and displayed detailed information about the files and directories in my system’s specified location ‘/home/nadiba/Documents’. However, the mkdir command failed as the specified directory already exists in ‘/home/nadiba/distro’.

2. Checking Exit Status Using && and || Operators

To check if a command fails or succeeds, use the && (logical AND) and || (logical OR) operators and conditionally execute different commands based on the output. The && operator executes only when the preceding command returns a zero exit status i.e. succeeds. On the contrary, the || operator executes only when the preceding command returns a non-zero exit status i.e. fails.

Check out the following script to check if a command fails or succeeds using the && and || operators:

#!/bin/bash

#Checking for successful execution
ls -l /home/nadiba/Downloads && echo "ls command executed successfully"

#Checking for failed execution
rm example.txt || echo "File doesn't exist. rm command execution failed."
EXPLANATION

In this script, if the ls command succeeds, the subsequent echo command will be executed using the && operator. For the next part, if the rm command fails, the subsequent echo command will be executed using the || operator.

Checking if a command succeeds or fails using logical AND (&&) and logical OR (||) operator in Bash

As you can see in the image the ls command executed successfully but the rm command failed as the file didn’t exist in the system.

How to Exit If a Command Fails in Bash?

Bash offers several methods to exit when a command fails such as using exit command, set -e option, set -eo pipefail option and set -u option. In the following section, I’ll explain how to use these methods to exit when a command fails in Bash.

1. Using “exit” Command

Calling the exit command with an exit code indicates immediate termination of the script’s execution. To exit if a command fails, use the exit code 1 with the exit command like the following script:

#!/bin/bash

#Command1
ls -l /home/Documents
if [ $? -ne 0 ]; then
    echo "ls command failed. Exit the script"
    exit 1
fi

#Command2
mkdir /home/distro/ubuntu
if [ $? -ne 0 ]; then
    echo "mkdir command failed. Exit the script"
    exit 1
fi
EXPLANATION

Here, if [ $? -ne 0 ] checks the exit status of the recently executed ls command. If the exit status is not equal to zero, the script exits using exit 1 without checking the further command.

Exit script using the exit command with exit code 1 if a command fails in Bash

As you can see from the image the ls command failed and so the script exits immediately without even executing the next command.

2. Using “set -e” Option

The set -e option instructs a Bash script to terminate as soon as a command fails, i.e., returns a non-zero exit status.

To check how to exit if a command fails using set -e option, check out the following Bash script:

#!/bin/bash

set -e

mkdir /home/example.txt
EXPLANATION

Here, set -e ensures that the script exits immediately if the mkdir command fails to execute.

Exit script using set -e option if a command fails in Bash

This images states that the mkdir command failed to create the directory ‘example.txt’ which leads the script to exit immediately.

3. Using “set -eo pipefail” Option

When a script contains multiple commands using piped statements, the set -eo pipefail option helps the script to exit if any command in the pipeline fails, not just the most recent one.

Following is a Bash script that exits using set -eo pipefail option when a command fails:

#!/bin/bash

set -eo pipefail

echo "The command runs"
#'find' command: Generates a list of files in /path/to/directory (including hidden ones)
#'sort' command: Sorts the list of files in reverse order
#'grep' command: Filters out lines that contain the word "Linux"
find /home/nadiba/distro -type f | sort -r | grep -v "Linux"
echo "The command doesn't run"
EXPLANATION

Here, The set -eo pipefail ensures that the script exits as soon as any command either “find”, “sort” or “grep” inside the pipeline fails.

Exit script using set -eo pipefail option if a command fails in Bash

In the above image, you can see that the find command failed to list the files in ‘/home/nadiba/distro’ which causes the script to exit immediately without even executing the last echo command.

4. Using ‘set -u’ Option

The set -u option is generally used at the start of a script where the -u option stands for nounset. When enabled, the “set -u” option terminates the script if there is any undefined or uninitialized variable.

Here’s a Bash script showing how to exit using set -u when a command fails:

#!/bin/bash

#nounset
set -u

echo "The command runs"
echo $non_existing_variable
echo "The command doesn't run"
EXPLANATION

Here, set -u treats the unset or uninitialized variable $non_existing_variable as an error and causes the script to exit immediately.

Exit script using set -u option when found an uninitialized variable in Bash

From the image, you can see that the script referenced the unset variable as an unbound variable error which instructs the script to exit immediately.

Conclusion

So far, this article described different methods to check if a command fails or succeeds in Bash as well as to exit if a command fails in Bash. To conclude, having a good knowledge of these methods ensures the reliability and robustness of Bash scripts. In fact, verifying the exit status of a command really helps in error handling and automating tasks based on different command executions.

People Also Ask

How to check if a command fails in Bash?

To check if a command fails in Bash, use the special variable $? inside conditional statements. To do this, use the if [ $? -ne 0 ] syntax to check if the exit status of the command is not equal to zero. Usually, a command that fails to execute will return a non-zero output. If the condition is true, it means that the command failed to execute.

How to check if a Bash command succeeds?

To check if a Bash command succeeds, use the syntax if [ $? -eq 0 ] that determines if the exit status of the command is equal to zero. A successful execution always returns a zero exit status. So, if the condition evaluates to true, it indicates the command executed successfully.

Can I immediately exit a script if any command fails in bash?

Yes, you can immediately exit a script if any command fails in Bash by enabling the set -e option at the start of the script. The ‘set -e’ option enables the errexit mode, which instructs the Bash script to terminate immediately when a command exits with a non-zero exit status i.e. fails or an error occurs.

Does a Bash script fail if a command fails?

No, by default a Bash script does not fail if a command fails. It continues executing subsequent commands without caring about earlier commands unless you set or enable certain options.

How to exit 1 if command fails in Bash?

To exit 1 if command fails in Bash, first explicitly check the exit status of the command using $? variable and then use the exit command with the exit code 1 if the command fails. For example:

#!/bin/bash

#Command1
ls -l /path/to/directory
if [ $? -ne 0 ]; then
    echo "ls command failed. Exit the script"
    exit 1
fi

#Command2
mkdir /path/to/directory
if [ $? -ne 0 ]; then
    echo "mkdir command failed. Exit the script"
    exit 1
fi

Can I check the exit status of a command in a function?

Yes, you can check the exit status of a command in a function using the special variable $?. For example:

#!/bin/bash

#Defining a function
command_check() {
    #Command execution
    ls -l /path/to/directory
    #Checking the exit status of the command
    if [ $? -eq 0 ]; then
        echo "Command succeeds"
    else
        echo "Command fails"
    fi
}

#Calling the function
command_check

Is there a shorthand method for checking command failure in Bash?

Yes, you can use the logical AND (&&) and logical OR (||) operators as a shorthand method  to check for command failure in Bash. For example:

#!/bin/bash

rm non_existent_file.txt && echo "The file removed successfully" || echo "File removal failed"


Related Articles


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

Rate this post
Nadiba Rahman

Hello, This is Nadiba Rahman, currently working as a Linux Content Developer Executive at SOFTEKO. I have completed my graduation with a bachelor’s degree in Electronics & Telecommunication Engineering from Rajshahi University of Engineering & Technology (RUET).I am quite passionate about crafting. I really adore exploring and learning new things which always helps me to think transparently. And this curiosity led me to pursue knowledge about Linux. My goal is to portray Linux-based practical problems and share them with you. Read Full Bio

Leave a Comment