You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Joachim Ansorg edited this page Nov 12, 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 ]
thenecho"bad input"fiif [ "$USER"-eq root ]
thenecho"You are root"fi
Correct code:
read -r n
if [ "$n"-lt 0 ] # Numerical comparisonthenecho"bad input"fiif [ "$USER"= root ] # String comparisonthenecho"You are root"fi
Rationale:
You are comparing a string value with a numerical operator, such as -eq, -ne, -lt or -gt. These only work for numbers.
If you want to compare the value as a string, switch to the equivalent string operator: =, !=\< or \>.
If you want to compare it as a number, such as n=42; while [ n -gt 1024/8 ]; .., then keep the operator and expand the operands yourself with $var or $((expr)): while [ "$n" -gt $((1024/8)) ]