[ubuntu-za] Script error
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
$ [ aa ] ; echo $? # not null, so true
$ [ -f ] ; echo $? # still not null
$ unset UNDEFINED # UNDEFINED is null
$ [ -f $UNDEFINED ] ; echo $? # still test for existance, even though null
$ [ $UNDEFINED ] ; echo $? # false, because it's null
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