[SGVLUG] bash scripting - checking for file existence
John E. Kreznar
jek at ininx.com
Fri Sep 10 23:54:28 PDT 2010
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
> if [ -e ]; then echo true; else echo false; fi
> # this prints true, shouldn't it be a syntax error?
man bash clarifies this case:
test and [ evaluate conditional expressions using a set
of rules based on the number of arguments.
0 arguments
The expression is false.
1 argument
The expression is true if and only if the
argument is not null.
2 arguments
If the first argument is !, the expression is
true if and only if the second argument is null.
If the first argument is one of the unary
conditional operators listed above under
CONDITIONAL EXPRESSIONS, the expression is true
if the unary test is true. If the first argument
is not a valid unary conditional operator, the
expression is false.
In " [ -e ] " there is only one argument and it's not null, so the
expression is true.
Superficial tests of dash and ash suggest that they behave the same as
bash. So I installed tcsh (on a throw-away virtual machine, not
wanting to clutter one of my working machines), and the results again
appear to be the same:
throw-away:~# echo $FILE | od -t x1 | head -1
0000000 0a
throw-away:~# [ -e $FILE ] ; echo $?
0
throw-away:~# [ -e "$FILE" ] ; echo $?
1
throw-away:~# [ -e "" ] ; echo $?
1
??
- --
John E. Kreznar jek at ininx.com 9F1148454619A5F08550 705961A47CC541AFEF13
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.10 (GNU/Linux)
Comment: Processed by Mailcrypt 3.5.8+ <http://mailcrypt.sourceforge.net/>
iEYEARECAAYFAkyLJ5EACgkQYaR8xUGv7xNEbACfbNNzMXsylFkk7hmUCTY191Bh
7B8AnjCT1kRcNl3Ad2+0I1NaqeilS1EZ
=yCTp
-----END PGP SIGNATURE-----
More information about the SGVLUG
mailing list