Why does `[ $var = "prod" ]` fail when `var` is empty or contains spaces?
IntermediateConceptArrays, conditionals and loops
Answer
[ is a command, so the unquoted variable is split before [ sees it. Empty var gives [ = prod ] → bash: [: =: unary operator expected. var="a b" gives [ a b = prod ] → bash: [: too many arguments.
[ "$var" = "prod" ] # fixed
[[ $var == prod ]] # Bash: no splitting inside [[ ]]
More on Arrays, conditionals and loops
How do you declare, populate and iterate an indexed array?BeginnerWhat is the difference between `"${arr[@]}"` and `"${arr[*]}"`?IntermediateHow do associative arrays work and what are they good for in DevOps scripts?IntermediateHow do you read a command's output into an array correctly?IntermediateWhat is the difference between `[ ]`, `[[ ]]` and `(( ))`?BeginnerList the most-used file test operators.Beginner