Comparing Strings and Numbers in Bash
Comparing variables is a fundamental operation in shell scripting, and Bash provides several ways to compare both strings and numbers. Selecting the right operators is crucial for writing correct and robust scripts. In this article, we'll walk through the syntax and usage of comparison operators like -eq
, -lt
, !=
, and ==
for both numeric and string comparisons in Bash.
Table of Contents
Numeric Comparisons in Bash
Bash uses specific operators for integer comparisons inside test brackets [ ... ]
or the test
command. Here are the most commonly used ones:
Operator | Meaning |
---|---|
-eq |
equal |
-ne |
not equal |
-lt |
less than |
-le |
less than or equal to |
-gt |
greater than |
-ge |
greater than or equal to |
Syntax Example:
a=5
b=10
if [ "$a" -lt "$b" ]; then
echo "$a is less than $b"
fi
Tip: Always quote your variables to prevent script errors if they are empty or contain spaces.
String Comparisons in Bash
Bash provides different operators for string comparison:
Operator | Meaning |
---|---|
= or == |
Strings are equal |
!= |
Strings are not equal |
< |
String is less than (ASCII order) |
> |
String is greater than (ASCII) |
-z |
String is null (zero length) |
-n |
String is not null |
Syntax Example:
str1="hello"
str2="world"
if [ "$str1" != "$str2" ]; then
echo "Strings are different."
fi
Note: In POSIX sh, use
=
for equality, not==
. In Bash, both can work inside[ ... ]
, but==
is generally reserved for[[ ... ]]
.
Common Pitfalls
- Do not mix up numeric and string operators. For example, using
==
for numeric comparison does not work as expected. - Do not forget to quote variables. Unquoted empty strings can lead to syntax errors.
- Use double brackets
[[ ... ]]
for advanced string comparison in Bash. Double brackets offer enhanced functionality, like pattern matching.
Practical Examples
1. Comparing Integers
num1=7
num2=15
if [ "$num1" -eq "$num2" ]; then
echo "They are equal."
elif [ "$num1" -lt "$num2" ]; then
echo "$num1 is less than $num2."
else
echo "$num1 is greater than $num2."
fi
2. Comparing Strings
word1="bash"
word2="shell"
if [ "$word1" == "$word2" ]; then
echo "Words are the same."
else
echo "Words are different."
fi
3. Check for Null or Empty String
input=""
if [ -z "$input" ]; then
echo "Input is empty."
fi
4. Lexicographical String Comparison
str1="apple"
str2="banana"
if [[ "$str1" < "$str2" ]]; then
echo "$str1 comes before $str2"
fi
Summary
Use operators like -eq
, -lt
, !=
, and ==
to compare numbers and strings in Bash. Remember:
- Use
-eq
,-lt
, etc., for numeric comparisons. - Use
!=
,==
(or=
),<
, and>
for string comparisons (prefer==
and!=
for equality and inequality). - Always quote your variables for safety.
- Use
[[ ... ]]
for advanced or pattern-based string testing in Bash-specific scripts.
Mastering these comparisons will help you write more reliable and readable Bash scripts!