Checking Whether Files Exist

Su Suriya Ravichandran Updated 06 Dec 2026
10 min read ·Lesson 71 of 205

Scripts work with files all the time: they read configuration, write logs, copy backups and delete old data. Before a script touches a file, it usually needs an answer to a simple question: is the file there? Bash answers this with file test operators, small flags such as -e and -f that you place inside [ ] or [[ ]]. Each one asks a question about a path and reports the answer through an exit status, so it plugs straight into the if statements from lessons 66 and 67.

Understanding the Concept

A file test does not read a file's contents. It asks the operating system about the path: does something exist there, what kind of thing is it, and how large is it? The answer is an exit status. 0 means the answer is yes and any other value means no, which is the same convention every condition in Bash follows.

A test on a path is a question about the moment it is asked. A file that exists now can be deleted a millisecond later by another process. For simple scripts this does not matter, but it is worth remembering when two programs share the same files.

Syntax

The general form is a unary operator followed by a path:

[ -e path ]
[[ -e path ]]

The operators used for existence checks are:

OperatorTrue when
-e pathanything exists at the path (file, directory, link target, device, and so on)
-f paththe path exists and is a regular file
-d paththe path exists and is a directory
-s paththe path exists and has a size greater than zero
-L path or -h paththe path is a symbolic link (it may point nowhere)

The operator ! in front of a test reverses the answer, so [ ! -e path ] is true when nothing exists at the path.

Basic Example

Create a small workspace to experiment with:

mkdir -p reports
printf 'hello\n' > notes.txt
: > empty.txt

The last line uses the : command, which does nothing, together with a redirection that creates an empty file. Now test some paths:

[ -e notes.txt ]; echo "-e notes.txt: $?"
[ -e reports ]; echo "-e reports: $?"
[ -e nothing.txt ]; echo "-e nothing.txt: $?"

Output:

-e notes.txt: 0
-e reports: 0
-e nothing.txt: 1

The -e operator is true for the file and for the directory, because both exist. It is false for nothing.txt, which does not exist.

Understanding the Example

Each line runs a test, then echo prints $?, the exit status of the test that just ran (lesson 43). Status 0 means true. In real scripts you rarely print the status. You place the test directly in an if:

file=notes.txt

if [ -e "$file" ]; then
    echo "$file exists"
else
    echo "$file is missing"
fi

Output:

notes.txt exists

The variable is quoted inside the test. This is the rule from lesson 55, and it matters even more for file names, which often contain spaces. The section on quoting below shows what happens without it.

Files Versus Directories

-e says that something exists, but it does not say what. When a script must know the type, use a more specific operator:

[ -f notes.txt ]; echo "-f notes.txt: $?"
[ -f reports ];   echo "-f reports: $?"
[ -d reports ];   echo "-d reports: $?"
[ -d notes.txt ]; echo "-d notes.txt: $?"

Output:

-f notes.txt: 0
-f reports: 1
-d reports: 0
-d notes.txt: 1

-f accepts regular files only. A directory exists, so -e is true for it, but -f is false. In the same way, -d is false for an ordinary file. When a script is about to read a file, -f is usually the right check. When it is about to enter a directory or write into one, use -d.

Checking for Empty Files

A file can exist and still contain nothing. The -s operator is true when the file exists and has at least one byte:

[ -s notes.txt ] ; echo "-s notes.txt: $?"
[ -s empty.txt ] ; echo "-s empty.txt: $?"
[ -s nothing.txt ]; echo "-s nothing.txt: $?"

Output:

-s notes.txt: 0
-s empty.txt: 1
-s nothing.txt: 1

The result for a missing file and for an empty file is the same, status 1. If you need to tell them apart, combine two tests, which the section on combining checks shows. The name -s stands for size, and it is easy to misread as "set" or "string".

A symbolic link is a small file that stores the path of another file. Most file tests follow the link and look at the target:

ln -s notes.txt link.txt
ln -s missing.txt broken.txt

[ -e link.txt ];   echo "-e link.txt: $?"
[ -L link.txt ];   echo "-L link.txt: $?"
[ -f link.txt ];   echo "-f link.txt: $?"
[ -e broken.txt ]; echo "-e broken.txt: $?"
[ -L broken.txt ]; echo "-L broken.txt: $?"

Output:

-e link.txt: 0
-L link.txt: 0
-f link.txt: 0
-e broken.txt: 1
-L broken.txt: 0

The last two lines show the key difference. broken.txt is a link whose target missing.txt does not exist. The -e test follows the link, finds nothing, and answers no. The -L test looks at the link itself and answers yes. The operator -h is a second name for -L and behaves the same way.

So a script that must detect a dangling link needs -L together with a negated -e:

if [ -L "$path" ] && [ ! -e "$path" ]; then
    echo "$path is a broken link"
fi

Quoting Paths Correctly

Paths often contain spaces, and an unquoted variable inside [ ] is split into separate words before the test runs (lesson 53). Create a file with a space in its name and compare the quoted and unquoted forms:

f="my notes.txt"
: > "$f"

[ -e "$f" ]; echo "quoted: $?"
[ -e $f ];   echo "unquoted: $?"

Output:

quoted: 0
bash: [: my: binary operator expected
unquoted: 2

Without quotes, Bash passes two words, my and notes.txt, to [, which does not understand that command line. It reports an error and returns status 2. In a script, the message begins with the script's name and a line number instead of bash:.

Inside [[ ]], the variable is not split, so [[ -e $f ]] works without quotes. Quoting is still a good habit, because the same line copied into a [ ] test would fail.

An empty variable behaves in a way that surprises many people:

p=""
[ -e "$p" ]; echo "-e empty string: $?"
[ -e ];      echo "-e alone: $?"

Output:

-e empty string: 1
-e alone: 0

With quotes, the test receives an empty path, and nothing has an empty name, so the answer is no. Without quotes the variable would vanish and the test would see only the word -e. A test with a single argument is true whenever that argument is not empty, so [ -e ] is true. This is the same rule that made [ -f/etc/hostname ] true in lesson 68, and it is one more reason to quote every variable.

Combining Checks

Use && and || to build richer conditions. Inside [[ ]] you can place them within one pair of brackets:

[[ -e notes.txt && -s notes.txt ]] && echo "exists and non-empty"

Output:

exists and non-empty

With [ ], write two separate tests and join them with the shell's own operators:

if [ -f "$file" ] && [ -s "$file" ]; then
    echo "$file is a non-empty regular file"
fi

Lesson 68 explained why -a and -o inside [ ] are best avoided, and lesson 74 covers logical operators in full.

Creating Things Only When Missing

A frequent pattern is "make sure this directory exists". Test first and create if needed:

[ -d out ] || mkdir out
[ -d out ] && echo "out exists now"

Output:

out exists now

The first line runs mkdir only when the directory test fails. For directories, mkdir -p does the job in one step. It creates the directory when it is missing, creates any missing parents, and returns status 0 when the directory already exists:

mkdir -p out
echo "status: $?"

Output:

status: 0

Use mkdir -p when the only goal is to guarantee that a directory exists. Use the explicit test when the script needs to do something different depending on the answer, such as printing a message on first creation.

Comparing Files

A few operators compare two paths instead of asking about one:

OperatorTrue when
file1 -nt file2file1 is newer (modified more recently) than file2
file1 -ot file2file1 is older than file2
file1 -ef file2both names refer to the same file
touch -d '2026-01-01' old.txt
touch -d '2026-06-01' new.txt

[ new.txt -nt old.txt ];  echo "new -nt old: $?"
[ old.txt -ot new.txt ];  echo "old -ot new: $?"
[ link.txt -ef notes.txt ]; echo "link -ef notes: $?"

Output:

new -nt old: 0
old -ot new: 0
link -ef notes: 0

The -nt operator is useful for build-style scripts that should rebuild an output only when its source has changed. The -ef operator answers yes for a symbolic link and its target, since both names lead to the same file.

Wildcards Inside File Tests

A pattern such as *.log is expanded by the shell before the test runs (lesson 52). That means [ -e *.log ] does not ask whether any log file exists. It asks a different question depending on how many files match:

[ -e *.log ]; echo "no log files: $?"
touch a.log b.log
[ -e *.log ]; echo "two log files: $?"

Output:

no log files: 1
bash: [: a.log: binary operator expected
two log files: 2

With no match, the pattern stays as the literal text *.log, no file has that name, and the test fails. With two matches, the test receives two names and reports an error. Neither form checks "does any log file exist".

The reliable approach is to loop over the pattern and test each result:

for f in *.log; do
    [ -e "$f" ] || continue
    echo "found $f"
done

Output:

found a.log
found b.log

The [ -e "$f" ] || continue line handles the case where nothing matched, because then $f holds the literal pattern, -e is false, and the loop skips it. Another option is the nullglob shell option, which makes an unmatched pattern disappear. Combined with an array, it gives a count:

shopt -s nullglob
logs=(*.log)
echo "count: ${#logs[@]}"
shopt -u nullglob

Output:

count: 2

Arrays are covered in lessons 97 to 101, and shopt in lesson 149.

Portability

All the operators in this lesson work with [ ] in Dash, the shell behind sh on Debian and Ubuntu. Running them through sh printed a success message for each of -e, -f, -L, -h and the -a combination. The [[ ]] form is Bash-specific:

sh -c '[[ -e notes.txt ]]'; echo "status: $?"

Output:

sh: 1: [[: not found
status: 127

If a script must run under sh, use [ ] with quoted variables and avoid [[ ]]. Lessons 188 and 189 return to portability in more detail.

Practical Applications

A script that reads a configuration file but falls back to defaults when the file is missing or empty:

#!/usr/bin/env bash

config="$HOME/.myapp.conf"

if [ -s "$config" ]; then
    echo "Using settings from $config"
else
    echo "No usable config at $config, using defaults"
fi

A script that refuses to continue when a required input is not a regular file:

#!/usr/bin/env bash

input="$1"

if [ ! -f "$input" ]; then
    echo "error: '$input' is not a regular file" >&2
    exit 1
fi

wc -l "$input"

Run as bash count.sh data.csv, the script prints the line count when data.csv exists. Run with a missing name, it prints the error to standard error (lesson 56) and exits with status 1, which lesson 118 explains further.

Questions such as "can this script write to that directory?" need permission tests such as -r, -w and -x, which the next lesson covers together with file types.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Checking Whether Files Exist and get answers drawn from it.

Signed-in readers only.