[ubuntu-za] Script error
Neil Muller
neil at dip.sun.ac.za
Tue Apr 14 14:37:17 BST 2009
On Tue, Apr 14, 2009 at 03:03:09PM +0200, Walter Leibbrandt wrote:
> ... Or zero.
>
> The following seems to always echo 1, ie. -f returns true if no
> parameters are specified:
> if [ -f ]; then echo 1; else echo 0; fi
That's because you're calling [ with only 1 argument, which returns true
if the arguement is non-null (as required by POSIX). Calling [ with 0
arguments is always false. The -f only acts as an existance test if
there are two arguments.
$ [ ] ; echo $? # always false
1
$ [ aa ] ; echo $? # not null, so true
0
$ [ -f ] ; echo $? # still not null
0
$ unset UNDEFINED # UNDEFINED is null
$ [ -f $UNDEFINED ] ; echo $? # still test for existance, even though null
1
$ [ $UNDEFINED ] ; echo $? # false, because it's null
1
The last can usefully be combined with the short-circuiting logic to
test parameters, although the [ "x$VAR" = "xVal" ] version is shorter.
Cryptic abuses of this logic left as an exercise for the reader.
-
Neil Muller email: neil at dip.sun.ac.za
Division Applied Mathematics, Department of Mathematical Sciences
University of Stellenbosch
More information about the ubuntu-za
mailing list