How to Check if a File or Directory Exists in Bash Scripts
In Bash, use [[ -f "$path" ]] to check that a regular file exists, [[ -d "$path" ]] for a directory, and [[ -e "$path" ]] for anything at that path. Add ! to test that it does not exist. Always quote variables, use [ ] instead of [[ ]] for portable POSIX sh scripts, and remember that a check can become out of date before you act on it, so handle errors from the actual operation too.
Topic: Linux Administration in IT Infrastructure · Comparison
Quick answer: In Bash, use [[ -f "$path" ]] to check that a regular file exists, [[ -d "$path" ]] for a directory, and [[ -e "$path" ]] for anything at that path. Add ! to test that it does not exist. Always quote variables, use [ ] instead of [[ ]] for portable POSIX sh scripts, and remember that a check can become out of date before you act on it, so handle errors from the actual operation too.
Key takeaways
-fregular file,-ddirectory,-eanything,-Lsymbolic link.- Quote paths:
"$file", to handle spaces. [[ ]]is Bash-specific;[ ]works in all POSIX shells.- Check permissions with
-r,-w,-x; non-empty with-s. - Run ShellCheck to catch common mistakes.
Table of Contents
- Which Test Operators Are Available?
- What Do Common Checks Look Like?
- Should You Use [ ] or [[ ]]?
- How Do You Check Several Files or a Pattern?
- How Do You Write a Reusable Check?
- What Mistakes Should You Avoid?
- References
Which Test Operators Are Available?
| Operator | True if the path |
|---|---|
-e | exists (any type) |
-f | is a regular file |
-d | is a directory |
-L or -h | is a symbolic link |
-s | exists and is not empty |
-r, -w, -x | is readable, writable, executable by you |
-p, -S, -b, -c | is a named pipe, socket, block or character device |
Full list in the Bash manual.
What Do Common Checks Look Like?
#!/usr/bin/env bash
config="/etc/myapp/config.yml"
logdir="/var/log/myapp"
if [[ -f "$config" ]]; then
echo "Config found"
else
echo "Config missing: $config" >&2
exit 1
fi
# Create a directory only if it does not exist
[[ -d "$logdir" ]] || mkdir -p "$logdir"
# Not exists
if [[ ! -e "/tmp/lockfile" ]]; then echo "No lock"; fi
# Exists and is not empty
[[ -s "$config" ]] && echo "Config has content"
Note that mkdir -p already succeeds if the directory exists, so the check is optional there.
Should You Use [ ] or [[ ]]?
[ ] / test | [[ ]] | |
|---|---|---|
| Portability | POSIX, works in sh, dash, ash | Bash, Zsh, Ksh only |
| Word splitting | Unquoted variables can break | Safer, but still quote |
| Extra features | None | Pattern matching, && and || inside |
Use [ ] in scripts that start with #!/bin/sh, as defined by the POSIX test utility.
How Do You Check Several Files or a Pattern?
# All required files present?
for f in /etc/myapp/config.yml /etc/myapp/key.pem; do
[[ -f "$f" ]] || { echo "Missing $f" >&2; exit 1; }
done
# Does any .log file exist? (globs do not work directly with -f when several match)
shopt -s nullglob
logs=(/var/log/myapp/*.log)
if (( ${#logs[@]} )); then echo "${#logs[@]} log files"; fi
How Do You Write a Reusable Check?
require_file() {
local path="$1"
if [[ ! -f "$path" ]]; then
printf 'Error: required file not found: %s
' "$path" >&2
return 1
fi
if [[ ! -r "$path" ]]; then
printf 'Error: cannot read: %s
' "$path" >&2
return 1
fi
}
require_file "/etc/myapp/config.yml" || exit 1
What Mistakes Should You Avoid?
- Unquoted variables:
[ -f $file ]fails with spaces or empty values. - Using
-fon a directory, or-don a file. - Check-then-act races: another process may delete or create the file between the check and the action (CWE-367). For security-sensitive files, open them directly and handle errors, and create temporary files with
mktemp. - Following symbolic links unintentionally; test
-Lfirst where it matters.
Run ShellCheck on scripts to find these issues automatically: shellcheck myscript.sh. Related: Linux admin commands. WebAsha offers Linux scripting courses.
References
Frequently Asked Questions
What's Your Reaction?
Like
0
Dislike
0
Love
0
Funny
0
Wow
0
Sad
0
Angry
0