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

File Tests (-f -d -e)

File tests are like peeking through the window to see if a house is there, and whether it is a house or a garden. You can ask if something exists, is a file, or is a folder.

In this page:

  1. File Tests (-f -d -e)
Syntax
bash
[[ -f path ]]
[[ -d path ]]
[[ -e path ]]

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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Forgetting spaces in [ -f "$file" ].
  2. Using -e when you need -f or -d, since -e is true for any type.
  3. Leaving the variable unquoted, which fails with names that have spaces.

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.