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.
- Knowing about the if $? in bash script.
- Learning about the uses of the $? sign in the if statement.
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
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:
➊ Open the Ubuntu Terminal.
➋ Write the following command in the command line to open a nano text editor:
➌ 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
➎ Then, press CTRL+S to save the file & press CTRL+X to exit the nano editor.
➏ Finally, run the script by the following command:
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.
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
Now, run the script by the following command:
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:
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
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:
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
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:
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
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:
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
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:
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
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:
➋ 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:
➍ 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
➌ Then, press CTRL+S to save the file & press CTRL+X to exit the nano editor.
➍ Finally, run the script by the following command:
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:
Now you will see the following output:
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.
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
- Check If a Variable Exists in Bash If Statement
- Check If An Input Argument Exists in Bash [4 Methods]
- Check If a String Contains Substring, Number & Letter in Bash
- Check If a String is Empty or Not in Bash [5 Methods]
- How to Compare Strings in Bash With if Statement [6 Methods]
- How to Compare Numbers in Bash With If Statement [2 Methods]
- Check If Array Contains an Element in Bash [6 Methods]
- Bash if-else Condition in One-Line [2 Ways]
- Using grep in if Statement in Bash [4 Cases]
- How to Use Regex in Bash If Condition? [4 Cases]
- Bash rm If Exists [All Case Explained]