Updated SC2170 (markdown)

Vidar Holen
2021-08-30 19:58:13 -07:00
parent 22e90bda5e
commit c0a516faf3

@@ -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:
@@ -8,16 +8,26 @@ if [ n -lt 0 ]
then
echo "bad input"
fi
if [ "$USER" -eq root ]
then
echo "You are root"
fi
```
### Correct code:
```sh
read -r n
if [ "$n" -lt 0 ]
if [ "$n" -lt 0 ] # Numerical comparison
then
echo "bad input"
fi
if [ "$USER" = root ] # String comparison
then
echo "You are root"
fi
```
### 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.
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: