Skip to content
Vidar Holen edited this page Aug 31, 2021 · 4 revisions

Invalid number for -eq. Use = to compare as string (or use $var to expand as a variable).

Problematic code:

read -r n
if [ n -lt 0 ]
then
   echo "bad input"
fi

if [ "$USER" -eq root ]
then
  echo "You are root"
fi

Correct code:

read -r n
if [ "$n" -lt 0 ]        # Numerical comparison
then
   echo "bad input"
fi

if [ "$USER" = root ]    # String comparison
then
  echo "You are root"
fi

Rationale:

You are comparing a string value with a numerical operator, such as -eq, -ne, -lt or -gt.

In [[ .. ]], this would automatically dereference the string, looking to see if there are variables by that name.

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, or $((n+1)) instead of n+1). If you are trying to compare strings and not numbers, use =, != \< or \> instead.

Exceptions:

None.

ShellCheck

Each individual ShellCheck warning has its own wiki page like SC1000. Use GitHub Wiki's "Pages" feature above to find a specific one, or see Checks.

Clone this wiki locally