[SGVLUG] bash scripting - checking for file existence - quoting arguments

Robert Leyva mrflash818 at geophile.net
Sat Sep 11 08:31:26 PDT 2010


According to the book "Classic Shell Scripting" by Robbins and Beebe
(O'Reilly book)

Chapter 6: Variables, Making Decisions, and Repeating Actions

For TEST:
"Arguments are required

For this reason, all shell variable expansions should be quoted so that
TEST receives an argument, even if it turns out to be the null string. For
example:

if[ -f "$file" ] ...  //correct
if[ -f $file ] ... //incorrect

In the second case, should $file happen to be empty, TEST receives one
less argument than it needs, leading to strange behavior
"

> 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)
> 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?
> # testing for --> -e '' <-- or --> -e "" <-- also prints true.  Why?
>
> if [ -e "$FILE" ]; then echo true; else echo false; fi
> # this prints false, as expected.  Why are the double quotes necessary?
>
> Yoshio
>


-- 
"Knowledge is Power" -- Francis Bacon

Robert Leyva
mrflash818 at geophile.net




More information about the SGVLUG mailing list