diff --git a/SC2170.md b/SC2170.md index 41c370b..62fc72e 100644 --- a/SC2170.md +++ b/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: @@ -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: