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

File Test Operators

File test operators let a script ask yes/no questions about a file, like whether it exists, is a folder, or can be written to.

Checking Existence

-e path is true if anything exists at that path at all (file, directory, symlink, etc). -f path narrows that down to "exists and is a regular file".

Example: Checking Existence

bash
#!/bin/bash
touch sample.txt
if [[ -e sample.txt ]]; then
    echo "sample.txt exists"
fi
if [[ -f sample.txt ]]; then
    echo "sample.txt is a regular file"
fi
rm -f sample.txt

Checking Directories

-d path is true only when the path exists and is a directory. This is the standard guard before cd-ing into a path or listing its contents.

Example: Checking Directories

bash
#!/bin/bash
mkdir -p sample_dir
if [[ -d sample_dir ]]; then
    echo "sample_dir is a directory"
fi
if [[ ! -d does_not_exist ]]; then
    echo "does_not_exist is not a directory"
fi
rmdir sample_dir

Checking Permissions

-r, -w, and -x check whether the current user has read, write, or execute permission on a path, respectively. These reflect actual OS-level permission checks, not just the file's mode bits.

Example: Checking Permissions

bash
#!/bin/bash
touch perm_test.txt
chmod 644 perm_test.txt
if [[ -r perm_test.txt ]]; then
    echo "readable"
fi
if [[ -w perm_test.txt ]]; then
    echo "writable"
fi
if [[ ! -x perm_test.txt ]]; then
    echo "not executable"
fi
rm -f perm_test.txt

Checking File Size

-s path is true when the path exists and its size is greater than zero bytes, which is a quick way to detect empty files before processing them.

Note: Combine tests with && or [[ -f a && -r a ]] to check several conditions at once.

Example: Checking File Size

bash
#!/bin/bash
touch empty.txt
echo "has content" > full.txt

if [[ ! -s empty.txt ]]; then
    echo "empty.txt is empty"
fi
if [[ -s full.txt ]]; then
    echo "full.txt has content"
fi
rm -f empty.txt full.txt
Common Mistakes
  1. Using -f to check "does this path exist" when it actually only means "exists and is a regular file"; a directory fails -f.
  2. Forgetting to quote the variable inside [ -f $var ], which breaks if the path contains spaces or is empty.
  3. Assuming -w and -x reflect the current user's actual effective permissions perfectly in every edge case (e.g. read-only filesystems), when they can occasionally be misleading.
Chapter Summary
  • -e tests existence of any kind; -f tests a regular file; -d tests a directory.
  • -r, -w, -x test read, write, and execute permission for the current user.
  • -s tests that a file exists and has a size greater than zero.
  • Prefer [[ ... ]] over [ ... ] in bash scripts; it handles unquoted variables and empty strings more safely.

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.