test file existence in bash
February 12th, 2007 by Lawrence David
file existence can be tested for in a conditional using the -a operator:
if [ -a filename.txt ]
then
echo “file here!”
fi
February 12th, 2007 by Lawrence David
file existence can be tested for in a conditional using the -a operator:
if [ -a filename.txt ]
then
echo “file here!”
fi
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”