mirror of
https://github.com/koalaman/shellcheck.git
synced 2025-10-03 19:29:44 +08:00
Updated SC2170 (markdown)
16
SC2170.md
16
SC2170.md
@@ -1,4 +1,4 @@
|
|||||||
## Numerical -eq does not dereference in [..]. Expand or use string operator.
|
## Invalid number for -eq. Use = to compare as string (or use $var to expand as a variable).
|
||||||
|
|
||||||
### Problematic code:
|
### Problematic code:
|
||||||
|
|
||||||
@@ -8,16 +8,26 @@ if [ n -lt 0 ]
|
|||||||
then
|
then
|
||||||
echo "bad input"
|
echo "bad input"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
if [ "$USER" -eq root ]
|
||||||
|
then
|
||||||
|
echo "You are root"
|
||||||
|
fi
|
||||||
```
|
```
|
||||||
|
|
||||||
### Correct code:
|
### Correct code:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
read -r n
|
read -r n
|
||||||
if [ "$n" -lt 0 ]
|
if [ "$n" -lt 0 ] # Numerical comparison
|
||||||
then
|
then
|
||||||
echo "bad input"
|
echo "bad input"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
if [ "$USER" = root ] # String comparison
|
||||||
|
then
|
||||||
|
echo "You are root"
|
||||||
|
fi
|
||||||
```
|
```
|
||||||
### Rationale:
|
### Rationale:
|
||||||
|
|
||||||
@@ -27,7 +37,7 @@ In `[[ .. ]]`, this would automatically dereference the string, looking to see i
|
|||||||
|
|
||||||
In `[ .. ]`, which you are using, the string is just treated as an invalid number.
|
In `[ .. ]`, which you are using, the string is just treated as an invalid number.
|
||||||
|
|
||||||
If you want to compare numbers, expand yourself (e.g. use `$var` instead of `var`). If you are trying to compare strings and not numbers, use `=`, `!=` `\<` or `\>` instead.
|
If you want to compare numbers, expand yourself (e.g. use `$var` instead of `var`, or `$((n+1))` instead of `n+1`). If you are trying to compare strings and not numbers, use `=`, `!=` `\<` or `\>` instead.
|
||||||
|
|
||||||
### Exceptions:
|
### Exceptions:
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user