Check for a File
if [ -f /etc/nginx/nginx.conf ]; then
echo "Nginx config found"
else
echo "No Nginx config"
fi
-f is true when the path exists and is a regular file. A symbolic link to a regular file also counts. The spaces inside the brackets are required. The if statement itself is explained in Bash if statement.
Check for a Directory
if [ -d /var/www/html ]; then
echo "Web root exists"
fi
Use -e when any type of entry is fine: file, directory, device, or socket.
The Test Operators
| Test | True when the path |
|---|---|
-e | Exists, any type |
-f | Is a regular file |
-d | Is a directory |
-s | Exists and is not empty |
-r | Is readable by you |
-w | Is writable by you |
-x | Is executable by you |
-L | Is a symbolic link |
-r, -w, and -x check the permissions of the user who runs the script. A link whose target is missing fails -e but passes -L.
Negate a Test
config=/etc/myapp/config.yml
if [ ! -f "$config" ]; then
echo "Missing: $config" >&2
exit 1
fi
The ! needs a space on both sides.
Single or Double Brackets
[ ] is the test command and works in every POSIX shell. [[ ]] is Bash syntax: it does not split variables on spaces, and it allows && and || inside. With single brackets, always quote the variable:
file="my report.pdf"
[ -f $file ] # fails: the name splits into two words
[ -f "$file" ] # correct
[[ -f $file ]] # also correct in Bash
Quoting also protects you from an empty variable. [ -f $file ] with an empty file becomes [ -f ], which is true, because a single word in brackets only tests that the word is not empty.
One-Line Checks
[ -f /etc/os-release ] && echo "exists"
[ -d /backup ] || mkdir /backup
[ -f "$file" ] && echo "yes" || echo "no"
In the third line, the part after || also runs if the middle command fails. That is harmless for echo, but use a full if statement for anything more.
When No Check Is Needed
Some commands handle the case themselves. mkdir -p /backup creates the directory only if it is missing and does not complain otherwise, so the check in the second line above is not needed. In general, a file can appear or vanish between the check and the next command. For important steps, try the operation and handle its failure:
if ! cp /etc/myapp/config.yml /var/backups/; then
echo "Backup of config failed" >&2
exit 1
fi
Check Several Files
missing=0
for f in /etc/hosts /etc/fstab /etc/myapp/config.yml; do
if [ ! -e "$f" ]; then
echo "Missing: $f" >&2
missing=1
fi
done
[ "$missing" -eq 0 ] || exit 1
To test whether any file matches a pattern, use compgen -G '/var/log/myapp/*.log' > /dev/null; it succeeds when at least one file matches.
Wait Until a File Appears
for i in $(seq 1 60); do
[ -f /run/myapp/ready ] && break
sleep 1
done
[ -f /run/myapp/ready ] || { echo "Timed out" >&2; exit 1; }
This waits up to a minute and then gives up. An open-ended version with while is shown in Bash while loop, and the script around it in how to write and run a Bash script.