Check if a directory or file exists
Within a shell script we can test for the presence of directories and files. In this article we look at the basics and the more exotic options available.
Testing the presence and type of a file can be done using the test command. For shell scripts, it is more common to use the [
command. Yes, it is an actual command. However, it may also be available as a so-called builtin and part of the shell. To validate this for bash, run the compgen -b
command.
Check if a file exists
Let’s start with testing if a file exists. This can be done using the -e option.
MYFILE="/etc/passwd"
if [ -e "${MYFILE}" ]; then
echo "File exists"
fi
Very often we actually want to test if a file exists and is a regular file. In this common case it might be better to use the -f option instead.
MYFILE="/etc/passwd"
if [ -f "${MYFILE}" ]; then
echo "File exists an is a regular file"
fi
Is a file executable?
MYFILE="/etc/passwd"
if [ -x "${MYFILE}" ]; then
echo "File is executable"
fi
Check the presence of a directory
ETCDIR="/etc"
if [ -d "${ETCDIR}" ]; then
echo "Directory ${ETCDIR} exists"
else
echo "Error: Directory ${ETCDIR} does not exist"
exit 1
fi
Options
Option | Purpose |
---|---|
-b | File exists (type: block special) |
-c | File exists (type: character special) |
-d | File exists (type: directory) |
-e | File exists |
-f | File exists (regular file) |
-g | File exists with setgid bit set |
-G | File exists, owned by effective group ID |
-h | File exists (type: symbolic link), similar to -L |
-k | File exists, sticky bit set |
-L | File exists (type: symbolic link), similar to -h |
-N | File exists, modified since last read |
-O | File exists, owned by effective user ID |
-p | File exists (type: named pipe) |
-r | File exists, readable |
-s | File exists, size greater than 0 bytes |
-S | File exists (type: socket) |
-t | File descriptor is opened on a terminal, requires a file description instead of file |
-u | File exists, setuid bit set |
-w | File exists, write permission granted |
-x | File exists, execute or search permission granted |