Re: What's the disadvantage for script if [ $x = 'WORLD ];
- From: Miao Jiang <jiangfriend@xxxxxxxxx>
- Date: Tue, 22 Mar 2011 02:30:52 -0700 (PDT)
On Mar 22, 3:05 am, Ben Finney <ben+u...@xxxxxxxxxxxxxxx> wrote:
Miao Jiang <jiangfri...@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
Thank you. double quote is quite necessary, especially do something
with strings.
and I write a script to understand it more
test.sh
#!/bin/sh
for arg; do
echo $arg
done
x="! -z"
../test.sh $x = "HELLO"
output:
!
-z
=
HELLO
../test.sh "$x" = "HELLO"
output:
! -z
=
HELLO
.
- Follow-Ups:
- Re: What's the disadvantage for script if [ $x = 'WORLD ];
- From: Chris F.A. Johnson
- Re: What's the disadvantage for script if [ $x = 'WORLD ];
- From: Ben Finney
- Re: What's the disadvantage for script if [ $x = 'WORLD ];
- References:
- What's the disadvantage for script if [ $x = 'WORLD ];
- From: Miao Jiang
- Re: What's the disadvantage for script if [ $x = 'WORLD ];
- From: Ben Finney
- What's the disadvantage for script if [ $x = 'WORLD ];
- Prev by Date: Re: generating non repeating numbers within a range
- Next by Date: Re: generating non repeating numbers within a range
- Previous by thread: Re: What's the disadvantage for script if [ $x = 'WORLD ];
- Next by thread: Re: What's the disadvantage for script if [ $x = 'WORLD ];
- Index(es):
Relevant Pages
|