The $? is a special variable that holds the exit status of the last executed command in Bash. After executing a command, Bash sets $? to a numerical value indicating whether the command succeeded or failed.
Conventionally, a value of 0 means success, while any non-zero value typically signifies some sort of failure or error condition. This allows scripts to check the success or failure of previous commands and take appropriate actions based on that result. In this article, you’ll learn to use $? with if statement.
What is the If Statement in Bash?
The if statement in bash 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 ranging from 0 to 255 after completing every operation. The greater the value of the exit code, the more severe the error. When the exit code shows $?==0 in the return status, meaning that the executed command has run successfully. If it shows a non-zero value, it means the failure of the execution of the last executed command. Therefore, this sign is an excellent toolkit for handling errors and making decisions in bash script.
Here is the meaning of some common exit code:
Exit code | Meaning |
---|---|
0 | Command executed successfully. |
1 | Command execution failed for some unknown error. |
2 | Command execution failed for using shell builtins incorrectly. |
126 | Command execution failed due to the lack of permissions. |
127 | Command execution failed for not finding it in the PATH variable. |
128 | Command execution failed for trying to exit with invalid arguments such as using negative numbers or non-integers. |
255 | Command execution failed for trying to exit with a value greater than 255. |
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.
1. 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. Check the script below to verify the command with $?
:
#!/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
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.
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.
2. 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 see the procedure to know how to handle a loop with $?
:
#!/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
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 syntax [ $? -ne 0 ]
(exit code not equal to 0) inside the if condition verifies whether the ping command has failed.
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. Since the command is executed successfully, it immediately breaks the loop. That’s how this command controls lengthy loops.
3. 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 sript below to know the entire process:
#!/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
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.
In the /home/mou directory, file1.txt is saved. You can see in this picture that the checking of file1.txt has succeeded.
4. 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:
#!/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
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 non-zero, it will print ‘user does not exist’ by checking the username with $? variable.
You can see in this picture that user mou exists in my Ubuntu system.
5. 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, now follow the example mentioned here:
#!/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
Here, command -v checks the ncal command’s existence. The $? Checks the exit status of the command.
You can see in this image that the command ncal is available in my Ubuntu system.
6. 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:
#!/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
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.
You can see in this image that the command requires superuser privileges to run.
7. 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:
#!/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
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.
The apache2 service is not running here.
8. 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:
- Create a log file by opening a nano text editor:
nano logfile.txt
- Now create a bash script file using the same nano text editor:
nano logging.sh
- Now, write the following script inside the text editor:
#!/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
EXPLANATIONA 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
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.
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
- 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]
<< Go Back to If Else in Bash | Bash Conditional Statements | Bash Scripting Tutorial
FUNDAMENTALS A Complete Guide for Beginners