« Back to Shell scripting

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

OptionPurpose
-bFile exists (type: block special)
-cFile exists (type: character special)
-dFile exists (type: directory)
-eFile exists
-fFile exists (regular file)
-gFile exists with setgid bit set
-GFile exists, owned by effective group ID
-hFile exists (type: symbolic link), similar to -L
-kFile exists, sticky bit set
-LFile exists (type: symbolic link), similar to -h
-NFile exists, modified since last read
-OFile exists, owned by effective user ID
-pFile exists (type: named pipe)
-rFile exists, readable
-sFile exists, size greater than 0 bytes
-SFile exists (type: socket)
-tFile descriptor is opened on a terminal, requires a file description instead of file
-uFile exists, setuid bit set
-wFile exists, write permission granted
-xFile exists, execute or search permission granted

Feedback

Small picture of Michael Boelen

This article has been written by our Linux security expert Michael Boelen. With focus on creating high-quality articles and relevant examples, he wants to improve the field of Linux security. No more web full of copy-pasted blog posts.

Discovered outdated information or have a question? Share your thoughts. Thanks for your contribution!

Mastodon icon