Bash Test Operations in ‘If’ Statement

Bash test operation is a prominent way to use the built-in “test” command or the equivalent operator [ ] (square brackets) to check the validity of a conditional expression by returning exit status like 0 for (True/Success) and 1 for (False/Failure).

Performing Test Operations in ‘If’ Conditionals in Bash

The test command performs checks and makes decisions in different conditional cases such as numerical comparisons, string comparisons, file comparisons, etc. Following are 3 different schemes of Bash conditional tests.

Bash ‘if’ Conditional Test for Numerical Comparison

Numerical comparison in Bash means comparing two numbers or numeric variables. However, conditional test operators that can be used for numerical comparison within the test command are: “-eq (equal)”, “-ne (not equal)”, “-gt (greater than)”, “-lt (less than)”, ‘-ge (greater than or equal)”, “-le (less than or equal)”.

1. Equality Comparison Using “-eq”

The “-eq” is an operator that checks if two numbers are equal. The line if [ "$num1" -eq "$num2" ] returns True if the $num1 and $num2 are equal. The script below shows the use of it:

#!/bin/bash

#Declaring two numbers
num1=6
num2=6

#Checking if the numbers are equal
if [ "$num1" -eq "$num2" ]; then
  echo "Equal Numbers"
fi
EXPLANATION
The script declares two variables num1 and num2. Then, it checks if the two numbers are equal using ‘[ ]’ within the ‘if’ statement and echoes the specific output using the echo command.

Two equal numbers checking using 'test' command

This output states that the inserted two numbers make the ‘if’ condition true and print “Equal Numbers”.

2. Inequality Comparison Using “-ne”

The “-ne” is an operator that checks if two numbers are not equal. So, to check whether the inserted two numbers are not equal, use the syntax if [ "$num1" -ne "$num2" ]. Following is an example to check if two numbers are not equal:

#!/bin/bash

#Declaring two numbers
num1=25
num2=5

#Checking if the numbers are not equal
if [ "$num1" -ne "$num2" ]; then
  echo "Not-equal Numbers"
fi

EXPLANATION
Here, the script first declares two variables num1 and num2. Then, it checks if the two numbers are not equal using ‘[ ]’ within the ‘if’ statement and displays the output using the echo command.

Checking if two numbers are not equal using 'test' command

The above image depicts that the script successfully satisfies the condition and displays “Not-equal Numbers”.

Similarly, you can use the operators “-gt”, “-lt”, ‘-ge”, “-le” and perform conditional test operations respectively.

Bash ‘if’ Conditional Test for String Comparison

When working with Bash scripts, sometimes you may need to compare strings in cases of equality, inequality, sorting and so on. In this effort, you can use these string comparison operators “= (equal)”, “!= (not equal)”, “> (greater than)”, “< (less than)”, “>= (greater than or equal)”, “<= (less than or equal)” within the test command.

1. Checking Null String Using “-z”

The “-z” is an operator that checks if a string is empty (zero length). If the condition [ -z "$string" ] within an “if” block is satisfied, it returns 0 (success) and executes the code of that block. Here is a detailed example:

#!/bin/bash

#Defining a string
string=""

#Checking if the string is empty
if [ -z "$string" ]; then
  echo "Empty String"
fi

EXPLANATION
First, the script defines a variable string. Then it checks if the string has zero length using the “-z” operator in the ‘[ ]’ command and displays the output “Empty String”.

Checking if the string is empty using 'test' command

From the above image, you can see that the declared variable string contains zero-length which means the string is empty.

2. Checking Non-empty String Using “-n”

The “-n” is an operator that checks whether a string is non-empty (non-zero length). And this is done by using the syntax if [ -n "$string" ]. For instance:

#!/bin/bash

#Defining a string
string="Hello, Linux!"

#Checking if the string is not empty
if [ -n "$string" ]; then
  echo "Not Empty String"
fi

EXPLANATION
This script first defines a string and then checks if the string has a non-zero length using the -n operator and displays “Not Empty String”.

Checking if the string is not empty using 'test' command

The above image states that the inserted variable length is non-zero meaning that it is a non-empty string.

3. Equality Checking Using “=”

The “=” is an operator that checks if two strings are equal. The syntax if [ "$String1" = "$String2" ] does the equality checking of the strings. Here’s an example for you:

#!/bin/bash

#Defining two strings
String1="Hi, Linux!"
String2="Hi, Linux!"

#Checking if the strings are equal
if [ "$String1" = "$String2" ]; then
  echo "Equal strings"
fi

EXPLANATION
This script declares two variables String1 and String2, then checks if the two strings are equal using the ‘=’ operator and displays the output “Equal strings”.

Checking if two strings are equal using 'test' command

The above image is a demonstration of equality checking of two strings.

4. Inequality Checking Using “!=”

The “!=” is an operator that verifies and returns true if two strings are not equal. Only using the syntax if [ "$String1" != "$String2" ] is enough to perform the inequality check. Let’s have a look at the following example:

#!/bin/bash

#Defining two strings
String1="Hi, Linux!"
String2="Hi, Windows!"

#Checking if the strings are not equal
if [ "$String1" != "$String2" ]; then
  echo "Not Equal Strings"
fi

EXPLANATION
This Bash script declares two variables String1 and String2, checks if the two strings are not equal using the  ‘!=’ operator and displays the output “Not Equal Strings”.

Checking if two strings not equal using 'test' command

In the above image, you will see a demonstration of inequality checking of two strings.

Bash ‘if’ Conditional Test for File & Directory Comparisons

Conditional testing is not only confined to numerical and string comparisons. Several file and directory operations can be performed using the test command in ‘if’ conditional statements in Bash.

Some common test operations can be implemented on files and directories using some Unary Operators where the output becomes true only for the existing file and directory that contains the following characteristics:

Unary Operators Purposes
-d Checks if it is a directory.
-e Checks if a file/directory exists.
-f Checks if it is a regular file.
-h / -L Checks if an existing file is a symbolic link.
-r Checks if a file is readable.
-s Checks if a file size is greater than zero.
-x Checks if a file is executable.
-w Checks if a file is writable.
-N Checks if an existing file has been modified since it was last read.
-S Checks if a file is a socket file.

The following example can be a helpful demo for you to understand how to perform a simple test operation on a file:

#!/bin/bash

#Checking if the file is executable
file="file1.sh"
if [ -x "$file" ]; then
  echo "$file is executable."
fi

EXPLANATION
The Bash script assigns a script file to a variable and then checks if the file is executable using [ -x “$file” ] and displays the output “file1.sh is executable”.

Checking if the file is executable using 'test' command

The above image describes that the assigned file file1.sh is executable.

According to the context of the previous discussion, you can perform conditional tests on pairs of files too by using Binary Operators like “-ot (Checks if a file is older than another one)”, “-nt (Checks if a file is newer than another one)” and so on.

Conclusion

The whole article provides you a proper knowledge of how you can perform different conditional tests in Bash. So, whether it’s for checking numeric values, file permissions, string comparisons, or verifying logical conditions, the test command always empowers you to make proper decisions and create responsive scripts by automating your tasks.

People Also Ask

Is there a shorthand for combining conditions in an ‘if’ statement using the ‘test’ command?

Yes, you can use the logical operators ‘-a (AND)’ or ‘-o (OR)’ within the square brackets as a shorthand for combining conditions in an ‘if’ statement in Bash using the ‘test’ command. For example, [ condition1 -o condition2 ]

Is there any difference between the = and == operators in the ‘test’ command when comparing strings in an ‘if’ statement?

No, there is no difference between the ‘=’ and ‘==’ operators in the ‘test’ command. Both operators are equivalent and you can use any one of your choice when comparing strings in an ‘if’ statement.

How to If a string starts with a specific prefix using the ‘test’ command in an ‘if’ statement?

To check if a string starts with a specific prefix, use a string operator with ‘#’. Here’s the syntax you can follow where the conditional checks if the string starts with a prefix: if [ "${string#prefix}" = "$string" ]

Is there a way to check If a string ends with a specific suffix using the ‘test’ command in an ‘if’ statement?

Yes, you can use a string operator with ‘%’ in an ‘if’ statement in a format like if [ "${string%suffix}" = "$string" ] to check if the string ends with a specific suffix.

Can I use wildcard patterns with the ‘test’ command in an ‘if’ statement to match filenames?

Yes, you can use wildcard patterns with the ‘test’ command in an ‘if’ statement to match filenames. For instance, if [ -f *.sh ] checks if there exist any files with the ‘.sh’ extension in the current directory.

How to test If a command is running?

To test if a command is running, use the ps aux command and then pipe the output to grep. This ‘ps (process status)’ command checks the list of running processes and the ‘grep’ command then looks for the particular command/process. For example:

#!/bin/bash

#Specifying the process name
process="X"

#Checking if the process is running
if ps aux | grep -q "$process"; then
  echo "Yes! $process is running."
fi

Related Articles


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

Rate this post
LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now
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