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.
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 are used to compare numbers.
| Operator | Meaning |
|---|---|
-eq | Equal to |
-ne | Not equal to |
-gt | Greater than |
-lt | Less than |
-ge | Greater than or equal to |
-le | Less 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 are used to compare text values.
| Operator | Meaning |
|---|---|
== | Equal to |
!= | Not equal to |
-z | String is empty |
-n | String 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
Bash also provides operators to check files and directories.
| Operator | Meaning |
|---|---|
-f | File exists |
-d | Directory exists |
-e | File or directory exists |
-r | File is readable |
-w | File is writable |
-x | File is executable |
Example:
#!/bin/bashfile="/etc/passwd"if [[ -f "$file" ]]; then echo "File exists"else echo "File does not exist"fi
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.
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.