I know that MyVar="a b" ; [ $MyVar = "a b" ]
will signal an error because the resultant expansion is [ a b = "a b" ]
.
I tried to avoid that case:
$ MyVar="\"a b\""
$ [ $MyVar = "a b" ]
-bash: [: too many arguments
Why did I fail? Didn't it expand to [ "a b" = "a b" ]
?
I know there is a [[ ... ]]
form; I know I can write "$MyVar"
.
I am asking why is my approach ineffective.
why is my approach ineffective.
That's because $MyVar
without quotes will be split into
"a
and b"
(two strings) and the ==
operator only works with one argument on the left hand side and one argument on the right hand side.
Note that parameter expansion is a one-pass thing. It expands the variable $MyVar
into "a
and b"
and does then not reevaluate the result. The order in which the expansions occur is listed in Shell expansion:
The order of expansions is: brace expansion; tilde expansion, parameter and variable expansion, arithmetic expansion, and command substitution (done in a left-to-right fashion); word splitting; and filename expansion.