Re: if [[ $Something ]] – in what situations does this work?
Robert P. J. Day
rpjday at crashcourse.ca
Sat Feb 18 15:41:39 UTC 2012
On Sat, 18 Feb 2012, J wrote:
> On Sat, Feb 18, 2012 at 10:02, Robert P. J. Day <rpjday at crashcourse.ca> wrote:
> > On Sat, 18 Feb 2012, franz.reitinger wrote:
> >
> >> First of all I suppose you're using the bash.
> >> Amoung others the shell treats several parameters specially; these
> >> parameters may only be referenced and assignement to them is not
> >> allowed.
> >>
> >> One of them is $?, which expands to the exit status of the most
> >> recently executed command. However, the exit status 0 means that the
> >> command has been executed without errors; any other return value has to
> >> be interpreted as error code.
> >> e.g.
> >> # any command ...
> >> if [ $? -ne 0 ]; then
> >> # error handling
> >> fi
> >
> > i'd have to check but i think the constuct
> >
> > if [[ $VAR ]]
> >
> > does nothing but check if either that variable is defined, or if it
> > has a non-zero string length. so no matter what the value of $? is,
>
> Correct:
>
> bladernr at klaatu:~$ A=foo
> bladernr at klaatu:~$ if [[ $A ]]; then echo YES; fi
> YES
> bladernr at klaatu:~$ if [[ $B ]]; then echo YES; fi
>
> AFAIK, that syntax will only work on user defined variables...
a simpler sequence of statements demonstrating that:
$ cat /etc/passwd
...
$ [[ $? ]] && echo yup
yup
$ cat /etc/paswd
No such file
$ [[ $? ]] && echo yup
yup
$
obviously, the value of $? is different in those two cases, but
testing it as above evaluates to "true" each time.
again, if you're testing $?, you should do an actual comparison.
rday
p.s. not to brag or anything but if you have a copy of o'reilly's
"classic shell scripting", yes, that's my name in the
acknowledgements. :-)
--
========================================================================
Robert P. J. Day Ottawa, Ontario, CANADA
http://crashcourse.ca
Twitter: http://twitter.com/rpjday
LinkedIn: http://ca.linkedin.com/in/rpjday
========================================================================
More information about the ubuntu-users
mailing list