[SGVLUG] bash scripting - checking for file existence
Byrne, Dj (313I)
djbyrne at jpl.nasa.gov
Fri Sep 10 20:37:11 PDT 2010
On Sep 10, 2010, at 7:32 PM, John E. Kreznar wrote:
> In a posting purportedly from yoshio <ak209 at lafn.org> but lacking a
> digital signature, it is written:
>
>> In bash, you can check for the existence of a file with "-e", like:
>
>> if [ -e /bin/true ]; then echo true; else echo false; fi
>> # this prints true, as expected
>
>> However, when I tried this:
>> FILE=$(which NoSuchFile)
>
> And not even this is necessary. I tried your tests first with FILE
> not defined at all (as revealed by "set"), and got the same results.
>
>> if [ -e $FILE ]; then echo true; else echo false; fi
>> # this prints true, even though there is no such file. Why?
>
>> if [ -e ]; then echo true; else echo false; fi
>> # this prints true, shouldn't it be a syntax error?
>
> Hmm. Bugs in bash? Or are we both overlooking something?
>
>> # testing for --> -e '' <-- or --> -e "" <-- also prints true. Why?
>
> My results are the opposite, if by this you mean:
>
> ~ $ if [ -e "" ] ; then echo true ; else echo false ; fi
> false
>
> ~ $ if [ -e '' ] ; then echo true ; else echo false ; fi
> false
I get the same results as John, and agree that the test function
should not return true when an argument is missing. Yoshio's
use of
FILE=$(which NoSuchFile)
is the same as [ -e ] (missing argument to test) and is
different from [ -e '' ] (empty string is passed as an argument).
BTW, I believe that while [ and test are synonyms for the
same bash builtin function, /bin/test is a separate executable
and may behave differently. Though in this case they behave
the same.
% [ -e /tmp ] ; echo $? # Existing directory is TRUE
0
% test -e /tmp ; echo $?
0
% [ -e ] ; echo $? # Missing argument is TRUE ???
0
% test -e ; echo $?
0
% /bin/test -e ; echo $?
0
% test -e /t ; echo $? # Non-existent directory is FALSE
1
% test -e "" ; echo $? # Empty string as existing file is FALSE
1
% test -e '' ; echo $?
1
% FILE=/tmp
% test -e $FILE ; echo $?
0
% test -e "$FILE" ; echo $?
0
% FILE=''
% test -e $FILE ; echo $? # A null string is same as missing argument
0
% test -e "$FILE" ; echo $? # Passing empty (not null) string as argument
1
% bash --version
GNU bash, version 3.2.48(1)-release (x86_64-apple-darwin10.0)
Copyright (C) 2007 Free Software Foundation, Inc.
% uname -a
Darwin longboat.jpl.nasa.gov 10.4.0 Darwin Kernel Version 10.4.0: Fri Apr 23 18:28:53 PDT 2010; root:xnu-1504.7.4~1/RELEASE_I386 i386
More information about the SGVLUG
mailing list