Feed on

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

if [ -a filename.txt ]


echo “file here!”


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!

3 Responses 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”

    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”

  2. on 30 Oct 2019 at 2:16 pm Duane Off

    I discovered your page by mistake nevertheless i’m glad i’m here. Good stuff i’m reading.

  3. on 13 Nov 2019 at 11:27 pm Solomon Mapua

    I actually appreciate your help. This exta little bit of advice will undoubtedly be implemented.

Did I get this wrong? Let me know!

Trackback URI | Comments RSS

More blogs about http://desk.stinkpot.org:8080/tricks.