Cybersecurity Updates & Tools

Bash Comparison Operators Explained With Examples

Introduction

Bash comparison operators are used to compare values inside Bash scripts. These values can be numbers, strings, files, or command results. If you want your Bash script to make decisions, you must understand comparison operators.

Comparison operators are commonly used with if, else, elif, while, and case statements. They help Bash scripts check conditions such as whether two numbers are equal, a file exists, a string is empty, or one value is greater than another.

For beginners, Bash comparison operators are very important because they are the foundation of decision-making in Bash scripting.

What Are Bash Comparison Operators?

comparison operators allow you to test conditions. Based on the result, the script can perform different actions.

Basic syntax:

if [[ condition ]]; then    commandelse    commandfi

Example:

#!/bin/bashage=18if [[ $age -ge 18 ]]; then    echo "You are eligible"else    echo "You are not eligible"fi

Output:

You are eligible

Numeric Comparison Operators

Numeric comparison operators are used to compare numbers.

OperatorMeaning
-eqEqual to
-neNot equal to
-gtGreater than
-ltLess than
-geGreater than or equal to
-leLess than or equal to

Example:

#!/bin/basha=10b=5if [[ $a -gt $b ]]; then    echo "$a is greater than $b"else    echo "$a is not greater than $b"fi

Output:

10 is greater than 5

String Comparison Operators

String comparison operators are used to compare text values.

OperatorMeaning
==Equal to
!=Not equal to
-zString is empty
-nString is not empty

Example:

#!/bin/bashusername="admin"if [[ "$username" == "admin" ]]; then    echo "Access granted"else    echo "Access denied"fi

Output:

Access granted

Check if a string is empty:

#!/bin/bashname=""if [[ -z "$name" ]]; then    echo "Name is empty"else    echo "Name is not empty"fi

File Comparison Operators

Bash also provides operators to check files and directories.

OperatorMeaning
-fFile exists
-dDirectory exists
-eFile or directory exists
-rFile is readable
-wFile is writable
-xFile is executable

Example:

#!/bin/bashfile="/etc/passwd"if [[ -f "$file" ]]; then    echo "File exists"else    echo "File does not exist"fi

Using Multiple Conditions

You can combine multiple conditions using && and ||.

Example:

#!/bin/bashuser="admin"password="12345"if [[ "$user" == "admin" && "$password" == "12345" ]]; then    echo "Login successful"else    echo "Login failed"fi

The && operator means both conditions must be true.

Conclusion

Bash comparison operators are essential for writing useful Bash scripts. They allow you to compare numbers, strings, files, and directories. By using operators like -eq, -gt, ==, !=, -f, and -d, you can create scripts that make decisions automatically.

Once you understand comparison operators, you can write better scripts for Linux automation, system checks, cybersecurity tasks, file monitoring, and user input validation.