Before attempting to open, read, or execute files in automated Bash deployment scripts, verifying that target files or directories exist prevents script crashes and unexpected state errors.
Bash File Test Operators Quick Reference
#!/usr/bin/env bash
FILE_PATH="/etc/nginx/nginx.conf"
DIR_PATH="/var/log/nginx"
# 1. Check if Regular File Exists (-f)
if [[ -f "${FILE_PATH}" ]]; then
echo "Regular file ${FILE_PATH} exists."
fi
# 2. Check if Directory Exists (-d)
if [[ -d "${DIR_PATH}" ]]; then
echo "Directory ${DIR_PATH} exists."
fi
# 3. Check if File Exists AND is Non-Empty (-s)
if [[ -s "${FILE_PATH}" ]]; then
echo "File exists and contains data."
fi
# 4. Check if File does NOT exist (! -f)
if [[ ! -f "/tmp/lockfile.pid" ]]; then
echo "Lockfile does not exist. Safe to proceed."
fi
Comments and corrections