← Back to Bash Course | Chapter 9: File Testing & Filesystem | Lesson 1 of 13

File Tests (-f -d -e)

In this page:

  1. File Tests (-f -d -e)

File Tests (-f -d -e)

[[ -f path ]] tests whether a path exists and is a regular file, [[ -d path ]] tests for a directory, and [[ -e path ]] tests for existence of either. These conditional file tests are essential before reading, writing, or acting on a path you're not certain exists. Combine them with ! to test the opposite, like [[ ! -f path ]].

Note: -e checks "exists at all"; -f and -d are more specific about what kind of thing it is.

Example: File Tests (-f -d -e)

bash
#!/bin/bash
touch sample.txt
mkdir -p sample_dir

if [[ -f sample.txt ]]; then
    echo "sample.txt is a regular file"
fi

if [[ -d sample_dir ]]; then
    echo "sample_dir is a directory"
fi

if [[ -e nonexistent.txt ]]; then
    echo "This won't print"
else
    echo "nonexistent.txt does not exist"
fi

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.