Feed on
Posts
Comments

file existence can be tested for in a conditional using the -a operator:

if [ -a filename.txt ]

then

echo “file here!”

fi


Bookmark and Share

if that was helpful ...

check out the other tips and tricks i've compiled on these pages. you might learn something else interesting!

One Response to “test file existence in bash”

  1. on 16 Jul 2012 at 6:45 am Rob Stewart

    There’s a problem with what you posted, and I have a couple of suggestions.

    First, the problem is that -a is the logical AND operator for test. What you actually want is -e, which tests for existence. You might also want to know whether the file is readable, for example, so you can use -r instead, though -r fails for both no file and unreadable file. Refer to, for example, http://ss64.com/bash/test.html for other tests you can use.

    Second, I like to keep “then” on the first line, so I’d write:

    if [ -e filename ]; then
    echo “found it”
    fi

    Second, when the action is a single line, as shown, you can simplify your example to the following:

    [ -e filename ] && echo “found it”

    There’s also || for logical OR’ing:

    [ -e somefile ] || echo >&2 “somefile missing”

Did I get this wrong? Let me know!

Trackback URI | Comments RSS