-eq vs == in Bash: Key Differences and Usage
-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 comparison | Numeric equality | String equality |
| Used inside | Arithmetic test [[ ]] or [ ] | String test [[ ]] |
| Syntax example | [ "$a" -eq "$b" ] | [[ "$a" == "$b" ]] |
| Error if used with wrong type | Yes, error if strings | No error but compares strings |
| Supported in | POSIX test and Bash | Bash [[ ]] and test (extension) |
| Typical use case | Compare numbers like 5 and 10 | Compare 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.
#!/bin/bash num1=5 num2=5 if [ "$num1" -eq "$num2" ]; then echo "Numbers are equal" else echo "Numbers are not equal" fi
== Equivalent
Here is the equivalent example using == to compare two strings.
#!/bin/bash str1="hello" str2="hello" if [[ "$str1" == "$str2" ]]; then echo "Strings are equal" else echo "Strings are not equal" fi
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.-eq inside [ ] or [[ ]] for numbers only.== inside [[ ]] for string comparison.-eq with strings to prevent errors.