Home > Back-end >  [[ $var -eq 0 ]] returns true even when the variable is unset, empty, or contains only spaces and ta
[[ $var -eq 0 ]] returns true even when the variable is unset, empty, or contains only spaces and ta

Time:03-18

This statement:

[[ $var -eq 0 ]]

returns true when var=0, when var is not defined, when var='' and when var=' ' (only spaces and tabs), I instead want the statement to return true only when var=0.

How can I get this?

CodePudding user response:

If you don't want var to be interpreted as a number (including trying to coerce non-numeric values into a reasonable numeric interpretation), use = instead to do a string comparison rather than a numeric one:

[[ $var = 0 ]]

Note that converting an empty string to 0 isn't the only coercion done when a non-numeric value is used in an arithmetic context. For an example of another one:

var1='var2'
var2=3
[[ $var1 -eq 3 ]] && echo "Strings can be coerced to indirect references"
  • Related