mirror of
https://github.com/koalaman/shellcheck.git
synced 2025-10-03 19:29:44 +08:00
Created SC2071 (markdown)
30
SC2071.md
Normal file
30
SC2071.md
Normal file
@@ -0,0 +1,30 @@
|
||||
## > is for string comparisons. Use -gt instead.
|
||||
|
||||
### Problematic code:
|
||||
|
||||
```sh
|
||||
if [[ $var > 10 ]]
|
||||
then
|
||||
echo "Triggers when var=5 and var=20"
|
||||
fi
|
||||
```
|
||||
|
||||
### Correct code:
|
||||
|
||||
```sh
|
||||
if [[ $var -gt 10 ]]
|
||||
then
|
||||
echo "Correct numerical comparison"
|
||||
fi
|
||||
```
|
||||
### Rationale:
|
||||
|
||||
`<` and `>`, in both `[[` and `[` (when escaped) will do a lexicographical comparison, not a numerical comparison.
|
||||
|
||||
This means that `[[ 5 > 10 ]]` is true because 5 comes after 10 alphabetically. Meanwhile `[[ 5 -gt 10 ]]` is false because 5 does not come after 10 numerically.
|
||||
|
||||
If you want to compare numbers by value, use the numerical comparison operators `-gt`, `-ge`, `-lt` and `-le`.
|
||||
|
||||
### Exceptions:
|
||||
|
||||
None.
|
Reference in New Issue
Block a user