Bash by Example: File Operations
Bash 5.0+
Checking file attributes and types using test operators and conditional expressions, determining if paths exist as files or directories, verifying file permissions and ownership, testing file age and size, and implementing robust file validation logic in shell scripts.
Code
#!/bin/bash
file="example.txt"
dir="data"
# Create dummy files
touch "$file"
mkdir -p "$dir"
# Check if file exists (generic)
if [ -e "$file" ]; then
echo "$file exists"
fi
# Check if it is a regular file
if [ -f "$file" ]; then
echo "$file is a regular file"
fi
# Check if it is a directory
if [ -d "$dir" ]; then
echo "$dir is a directory"
fi
# Check read/write/execute permissions
if [ -r "$file" ]; then echo "Readable"; fi
if [ -w "$file" ]; then echo "Writable"; fi
if [ -x "$file" ]; then echo "Executable"; fi
# Check if file is empty
if [ -s "$file" ]; then
echo "File is not empty"
else
echo "File is empty"
fi
# Cleanup
rm "$file"
rmdir "$dir"Explanation
Bash provides a rich set of unary operators to test file attributes within [ ... ] or [[ ... ]] blocks. These are essential for robust scripts that interact with the filesystem, ensuring files exist before trying to read them or directories exist before trying to enter them.
The most common operators are:
-e: Exists (any type)-f: Exists and is a regular file-d: Exists and is a directory-s: Exists and size is greater than 0
You can also check permissions using -r (readable), -w (writable), and -x (executable). These checks respect the current user's permissions.
Code Breakdown
11
-e is the most basic check. It returns true for files, directories, symlinks, sockets, etc.16
-f is more specific. It returns false if the path is a directory, even if it exists. This is usually preferred when you intend to read/write content.31
-s checks if the file has content. It returns true if the file size is > 0 bytes.
