Re: What's the disadvantage for script if [ $x = 'WORLD ];



Miao Jiang <jiangfriend@xxxxxxxxx> writes:

Hello,
for script
x='HELLO'
if [ $x = 'HELLO' ];
some people write it in
if [ "$x" = 'HELLO' ];

Is there any disadvantage if write it in [ $x = 'HELLO' ] ?

Failing to quote variable expansions is a common mistake:

$ x="HELLO"
$ if [ $x = "HELLO" ] ; then printf "Equal\n" ; else printf "Unequal\n" ; fi
Equal

$ x="WORLD"
$ if [ $x = "HELLO" ] ; then printf "Equal\n" ; else printf "Unequal\n" ; fi
Unequal

$ x=""
$ if [ $x = "HELLO" ] ; then printf "Equal\n" ; else printf "Unequal\n" ; fi
bash: [: =: unary operator expected
Unequal

$ x="HELLO WORLD"
$ if [ $x = "HELLO" ] ; then printf "Equal\n" ; else printf "Unequal\n" ; fi
bash: [: too many arguments
Unequal

$ x="! -z"
$ if [ $x = "HELLO" ] ; then printf "Equal\n" ; else printf "Unequal\n" ; fi
Equal

If the variable can't be guaranteed to be a single word every time – if
it might be empty, or might contain characters special to the shell, or
might simply have a value not under your complete control – quote it
when expanding.

In general: quote any variable expansion unless you have a good reason
not to.

--
\ “Science shows that belief in God is not only obsolete. It is |
`\ also incoherent.” —Victor J. Stenger, 2001 |
_o__) |
Ben Finney
.



Relevant Pages