BASH
Robust File Existence and Permission Checks
Implement robust file existence and permission checks in Bash scripts using conditional expressions to ensure script reliability and prevent errors.
#!/bin/bash
FILE_TO_CHECK="/tmp/test_file.txt"
DIR_TO_CHECK="/var/log"
# --- Check for file existence and type ---
# Check if a file exists
if [[ -f "$FILE_TO_CHECK" ]]; then
echo "'$FILE_TO_CHECK' exists and is a regular file."
else
echo "'$FILE_TO_CHECK' does not exist or is not a regular file. Creating..."
touch "$FILE_TO_CHECK"
fi
# Check if a directory exists
if [[ -d "$DIR_TO_CHECK" ]]; then
echo "'$DIR_TO_CHECK' exists and is a directory."
else
echo "Error: '$DIR_TO_CHECK' does not exist or is not a directory."
exit 1
fi
# --- Check for permissions ---
# Check if file is readable
if [[ -r "$FILE_TO_CHECK" ]]; then
echo "'$FILE_TO_CHECK' is readable."
else
echo "Error: '$FILE_TO_CHECK' is not readable."
exit 1
fi
# Check if file is writable
if [[ -w "$FILE_TO_CHECK" ]]; then
echo "'$FILE_TO_CHECK' is writable."
else
echo "Error: '$FILE_TO_CHECK' is not writable."
exit 1
fi
# Check if directory is executable (searchable)
if [[ -x "$DIR_TO_CHECK" ]]; then
echo "'$DIR_TO_CHECK' is searchable (executable).
Can list its contents."
else
echo "Error: '$DIR_TO_CHECK' is not searchable (executable)."
exit 1
fi
# Clean up example file
rm -f "$FILE_TO_CHECK"
How it works: This script demonstrates how to perform essential file existence and permission checks in Bash using various conditional test operators. It checks if a given path is a regular file (`-f`), a directory (`-d`), readable (`-r`), writable (`-w`), or executable (`-x`). These checks are crucial for writing robust scripts that interact with the filesystem, ensuring that files and directories exist in the expected state and have the necessary permissions before attempting operations, thereby preventing common errors and improving script reliability.