0
0
Bash-scriptingComparisonBeginner · 3 min read

-eq vs == in Bash: Key Differences and Usage

In Bash, -eq is used to compare two numbers for equality, while == is used to compare two strings inside [[ ]]. Using -eq with strings or == with numbers can lead to unexpected results or errors.
⚖️

Quick Comparison

This table summarizes the main differences between -eq and == in Bash.

Aspect-eq==
Type of comparisonNumeric equalityString equality
Used insideArithmetic test [[ ]] or [ ]String test [[ ]]
Syntax example[ "$a" -eq "$b" ][[ "$a" == "$b" ]]
Error if used with wrong typeYes, error if stringsNo error but compares strings
Supported inPOSIX test and BashBash [[ ]] and test (extension)
Typical use caseCompare numbers like 5 and 10Compare strings like "foo" and "bar"
⚖️

Key Differences

The -eq operator in Bash is designed specifically for numeric comparison. It checks if two integers are equal. If you try to use -eq with non-numeric strings, Bash will throw an error because it expects numbers.

On the other hand, == is used for string comparison inside the double bracket test [[ ]]. It checks if two strings are exactly the same. It does not perform numeric comparison, so "5" == "05" is false because the strings differ.

Also, == is not POSIX standard inside single brackets [ ], but Bash supports it there as an extension. The safest string comparison is with double brackets [[ ]]. Numeric comparisons should always use -eq, -ne, -lt, etc.

⚖️

Code Comparison

Here is an example using -eq to compare two numbers.

bash
#!/bin/bash

num1=5
num2=5

if [ "$num1" -eq "$num2" ]; then
  echo "Numbers are equal"
else
  echo "Numbers are not equal"
fi
Output
Numbers are equal
↔️

== Equivalent

Here is the equivalent example using == to compare two strings.

bash
#!/bin/bash

str1="hello"
str2="hello"

if [[ "$str1" == "$str2" ]]; then
  echo "Strings are equal"
else
  echo "Strings are not equal"
fi
Output
Strings are equal
🎯

When to Use Which

Choose -eq when you want to compare numbers because it correctly handles numeric values and errors on invalid input. Choose == when comparing strings inside [[ ]] because it compares text exactly and avoids errors with non-numeric data. Mixing them can cause bugs or unexpected behavior.

Key Takeaways

-eq is for numeric equality; == is for string equality.
Use -eq inside [ ] or [[ ]] for numbers only.
Use == inside [[ ]] for string comparison.
Avoid using -eq with strings to prevent errors.
Always pick the operator that matches your data type to avoid bugs.