What is “$?” in the Bash if Statement? [8 Examples]

In Bash scripting, the if statement allows you to set conditions and will execute the output based on the condition you put. The $? sign in the if statement is usually not a part of it. However, it can be used with the conjunction of an if statement to check whether the last executed command is successful or not. This sign is mainly related to commands, it will show error messages in the exit status if any malfunction occurs in the bash script. Therefore, for error handling it is a great tool to use. To know more about it, read on.

Key Takeaways

  • Knowing about the if $? in bash script.
  • Learning about the uses of the $? sign in the if statement.

Free Downloads

What is the If Statement in Bash?

The if statement in bash basically sets the conditions and gives the output based on whether the condition is true or false. It will execute the outcome if the condition is true. You can set multiple conditions under this if statement.

The syntax of the if statement is:

if [condition]; then
# execute the code if the condition is true
fi
EXPLANATION

if: Denotes the starting of the condition.

[condition]: The condition is enclosed with square brackets ‘[ ]’.

then: Separates the condition from the execution code block.

# execute the code if the condition is true: Execution code block.

fi: Ending of the conditional statement.

What is the “$?” Sign in the If Statement in Bash?

The $? sign in the if statement is used to check the exit status of the previous command that executed last. Exit status is the status that shows a numerical value of 0 or 1 after completing every operation. It will show $?==0 in the return status which means the executed command has run successfully. If it shows $?==1, it means failure of the execution of the last command. Therefore, this sign is an excellent toolkit for handling errors and making decisions in bash script.

8 Practical Examples of Using If “$?” in Bash

The $? sign in the if statement is a particular variable that stores the numerical value to denote the return status of the last executed command. In this section, I will describe 8 examples of the $? sign in the if statement to let you know more about it. Let’s learn the detailed steps about how to use the $? sign in the If statement in Bash scripting.

Example 01: Verifying Success or Failure of the Command With an “if $?” Sign

You can verify whether the last executed command runs correctly with the if $?. In this example, I will generate a bash script where I will take two variables and compare them to see if variable 1 is equal/not equal to variable 2. After that, I will check the success and failure of the command execution through the exit status. Let’s dive into the detailed procedure:

Steps to Follow >

➊ Open the Ubuntu Terminal.

➋ Write the following command in the command line to open a nano text editor:

nano error.sh
EXPLANATION
  • nano: A text editor.
  • error.sh: A Bash script, named ‘error.sh’. You can name any according to your preferences.

➌ Now, write the following script inside the text editor:

Script (error.sh) >

#!/bin/bash

# Define two numbers for comparison
var1=10
var2=20

# Compare the numbers
if [ $var1 -eq $var2 ]; then
    echo "$var1 is equal to $var2"
else
    echo "$var1 is not equal to $var2"
fi

# Check the exit status of the comparison
if [ $? -eq 0 ]; then
    echo "Comparison succeeded. Exit status: $?"
else
    echo "Comparison failed. Exit status: $?"
fi
EXPLANATION

Here, in #! /bin/bash, ‘#!’ is called shebang or hashbang. It indicates the interpreter to be used for executing the script, in this case, it’s Bash. And I have put two variables to compare under the if else statement. The echo command echoes the quoted message. Lastly, I have checked if the comparison is successful or failed with the $? sign.

➎ Then, press CTRL+S to save the file & press CTRL+X to exit the nano editor.

➏ Finally, run the script by the following command:

bash error.sh

output of error.sh bash script

In this image, you can see that the number 10 is not equal to the number 20 which is true. Hence, the exit status is 0 (true) and the comparison is successful.

Example 02: Handling Loops With an “if $?” Sign in Bash

Handling lengthy loops is one of the most difficult tasks to do. However, the if $? can be used to control any loop. In this example, I will describe how the while loop can be controlled to check the network connection of the Linuxsimply website. Let’s know the procedure.

You can follow the Steps of Example 01, to save the bash script.

Script (loop.sh) >

#!/bin/bash
while true; do
    sleep 5  # Add a 5-second delay
    ping -c 1 linuxsimply.com

    if [ $? -ne 0 ]; then
        echo "Ping failed. Retrying..."
    else
        echo "Ping succeeded. Exiting loop."
        break
    fi
done
EXPLANATION

Here, while true; do will initiate the while loop. Then I added sleep 5 to make a 5-second delay before attempting each ping, then checked the ping of the Linuxsimply website with the ping -c 1 command. The last if [ $? -ne 0 ] condition verifies whether the ping command is successful or not.

Now, run the script by the following command:

bash loop.sh

checking network connection of the linuxsimply sebsite

In this image, you can see that ping has succeeded which means the network connection of Linuxsimply is alright. Additionally, after every iteration of the while loop, the if $? checks the exit status and immediately breaks the loop if any error is encountered. That’s how this command controls lengthy loops.

Example 03: Checking File’s existence With an “if $?” Sign

When you want to know if a particular file exists in your Linux system or not, you can check that with this if $?. Now for this example, I will check if file1.txt exists in my Linux system by checking the exit status. Follow the steps below to know the entire process:

You can follow the Steps of Example 01, to save the bash script.

Script (exist.sh) >

#!/bin/bash 
file_path="/home/mou/file1.txt" 

# Check if the file exists 
if [ -e "$file_path" ]; then 
echo "The file1 $file_path exists." 
else 
echo "The file1 $file_path does not exist." 
fi 

# Check the exit status of the file existence check
if [ $? -eq 0 ]; then 
echo "File1 check succeeded." 
else 
echo "File1 check failed." 
fi
EXPLANATION

To check the existence of the file1.txt in the /home/mou/ folder, a file path is defined named file_path=”/home/mou/file1.txt” which will search for the file1.txt in the /home/mou location in my Linux system using the if -e flag. The last if condition with $? is applied to verify the file check command.

checking file existence using bash if $?

In the /home/mou directory, file1.txt is saved. You can see in this picture that the checking of file1.txt has succeeded.

Example 04: Using “if $?” Sign to Check If User Exist in Bash

With id command and $? variable, you can inspect whether a user exists or not. In the following Bash script, I have created a user named mou to check its existence. After running the script, you will get information about the exit status. See the example below:

You can follow the Steps of Example 01, to save the bash script.

Script (user.sh) >

#!/bin/bash
username="mou"

# Check if the user exists
id "$username" &>/dev/null

# Check the exit status
if [ $? -eq 0 ]; then
echo "User $username exists."
else
echo "User $username does not exist."
fi
EXPLANATION

Here, id command checks the user’s presence. To keep both standard output and error to the /dev/null, the ‘&>’ prefix is used. If the exit status is 0, it will print user exists; if the exit status is 1, it will print ‘user does not exist’ by checking the username with $? variable.

checking if user exists in the system using $? in the if else statement

You can see in this picture that user mou exists in my Ubuntu system.

Example 05: Checking If Command Exist With an “if $?” Sign

Anyone can inspect the availability of a command using the if $? easily. In this section, I will check the ncal command in my Ubuntu which shows the calendar of the current months of the year. You can check any command according to your preferences, just follow the steps mentioned here:

You can follow the Steps of Example 01, to save the bash script.

Script (command.sh) >

#!/bin/bash
command_name="ncal"

# Check if the command is available
command -v "$command_name" &>/dev/null

# Check the exit status
if [ $? -eq 0 ]; then
echo "$command_name is available."
else
echo "$command_name is not available or not in the PATH."
fi
EXPLANATION

Here, command -v checks the ncal command’s existence. The $? Checks the exit status of the command.

checking the existence of ncal command

You can see in this image that the command ncal is available in my Ubuntu system.

Example 06: Using “if $?” Sign for Checking If Command Requires Superuser Privilege

Not all commands run immediately after executing the code. Some commands need superuser privileges to function such as installing, uninstalling, updating, or upgrading something that requires sudo facilities. Let’s know more about it:

You can follow the Steps of Example 01, to save the bash script.

Script (superuser.sh) >

#!/bin/bash

#Run the command to check superuser privileges
apt update

# Check the exit status
if [ $? -eq 0 ]; then
echo "The command does not require superuser privileges."
else
echo "The command may require superuser privileges."
fi
EXPLANATION

Here, the apt update command updates the package lists in Ubuntu. However, it requires sudo privileges to function which is checked with the exit status of $? variable.

checking if command requires sudo privileges

You can see in this image that the command requires superuser privileges to run.

Example 07: Checking If a Service is Running With an “if $?” Sign Bash

With id command and $? variable, you can check the existence of a service. In this example, I will describe to you how to check the active status of the Apache HTTP service by checking the exit status of the systemctl command. See the example below:

You can follow the Steps of Example 01, to save the bash script.

Script (service.sh) >

#!/bin/bash
service_name="apache2"

# Check if the Apache service is active (running)
systemctl is-active "$service_name" &>/dev/null

# Check the exit status
if [ $? -eq 0 ]; then
echo "Service $service_name is running."
else
echo "Service $service_name is not running."
fi
EXPLANATION

Here, systemctl is used to check if the service called ‘apache2’ is running. The $? variable checks the exit status of the systemctl command and makes the decision if the specified service is active or not.

checking if the apache2 service is running

The apache2 service is not running here.

Example 08: Logging Error Messages With an “if $?” Sign

Logging error messages in a particular file can be done with the if $? Sign. In this example, I will create a text file to redirect the error messages and output. If the code encounters any error, the exit status will check the output and send it into a log text file. To know how to do that, follow the steps below:

Steps to Follow >

➊ Create a log file by opening a nano text editor:

nano logfile.txt
EXPLANATION

logfile.txt: A text file to log both the output and error messages.

➋ Then, press CTRL+S to save the file & press CTRL+X to exit the nano editor.

➌ Now create a bash script file using the same nano text editor:

nano logging.sh
EXPLANATION

logging.sh: This is a script. Here, I have named the script ‘logging.sh’. You can name any according to your preferences.

➍ Now, write the following script inside the text editor:

Script (logging.sh) >

#!/bin/bash
log_file="logfile.txt"
checking_disk_space="df -h"

# Run the command and capture both stdout and stderr to the log f>
$checking_disk_space >> "$log_file" 2>&1

# Check the exit status
if [ $? -ne 0 ]; then

# Log an error message with the exit status
echo "$(date '+%Y-%m-%d %H:%M:%S') - Error: The command '$check>
fi
EXPLANATION

A text file called “logfile.txt” is created to log both output and error messages. The “df -h” command checks the disk space. Afterwards, the exit status is checked with $?. Here, in the log message to incorporate a timestamp “$(date ‘+%Y-%m-%d %H:%M:%S’) is used.

➌ Then, press CTRL+S to save the file & press CTRL+X to exit the nano editor.

➍ Finally, run the script by the following command:

bash logging.sh

It will print no output as I have logged the output and error message in the logfile.txt.

➎ Now to print the output in the logfile.txt, run the following command:

cat logfile.txt
EXPLANATION

cat: Displays the contents of a file.

Now you will see the following output:

checking the output of logging file

You can notice that the output is logged in the logfile.txt. As there is no error in the code, the error messages are not here.

Conclusion

In this article, I have explained how if $? works and different uses of it in bash script. In Bash, $? acts as a decision-maker who checks errors and ensures that you are doing great by verifying the last command you run. Additionally, you can check the file’s existence with this special variable $? under the if condition. You can control lengthy loops and check the success or failure of any command, service, or database backup with this operator. Therefore, carefully read this article to accomplish all these tasks.

People Also Ask

What is $* in a shell script?
This is a single string made up of all the positional parameters and it is separated by the 1st character of the environment variable which is by default a tab, space or newline.
How do you use $$ in a shell?
It is a variable that is the process identifier of the currently running shell. For making temporary files like /tmp/my-script, this can be helpful. $$, which is advantageous if multiple instances of the script might run concurrently and each one would require its temporary files.
What is $1 $2 $3 in a shell script?
  • $1 means the first argument is sent to the Bash script.
  • $2 means the second argument is sent to the Bash script.
  • $3 means the third argument is forwarded to the Bash script.

Related Articles


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

5/5 - (1 vote)
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