How to Check if Directory Exists in Bash
• 1 min read
bash file operations directory test conditional
Quick Answer: Check if Directory Exists in Bash
To check if a directory exists in Bash, use the -d operator: if [ -d "$dir" ]; then. This works with both absolute and relative paths. Combine it with -p in mkdir to create directories safely if they don’t exist.
Quick Comparison: Directory Testing Methods
| Operator | Purpose | Usage | Best For |
|---|---|---|---|
| -d | Directory exists | [ -d "$dir" ] | Simple existence check |
| -d && -r | Directory + readable | [ -d "$dir" -a -r "$dir" ] | Access verification |
| **-d | mkdir** | Create if missing | |
| ! -d | Directory missing | [ ! -d "$dir" ] | Negation tests |
| -x | Directory executable | [ -x "$dir" ] | Permission checks |
Bottom line: Use -d to check existence, combine with mkdir -p to auto-create.
Check if directories exist in Bash.
Basic Test
dir="/home/user"
if [ -d "$dir" ]; then
echo "Directory exists"
fi
Check and Create If Missing
backup_dir="/home/backups"
if [ ! -d "$backup_dir" ]; then
mkdir -p "$backup_dir"
echo "Created directory: $backup_dir"
fi
Check Multiple Directories
for dir in /tmp /var /home; do
if [ -d "$dir" ]; then
echo "Directory exists: $dir"
fi
done
Verify Directory Permissions
dir="/var/log"
if [ -d "$dir" ] && [ -r "$dir" ]; then
echo "Directory is readable"
fi
if [ -d "$dir" ] && [ -w "$dir" ]; then
echo "Directory is writable"
fi
if [ -d "$dir" ] && [ -x "$dir" ]; then
echo "Directory is executable"
fi
Practical Example: Backup Script
#!/bin/bash
backup_dir="/home/backups"
source_dir="/home/user"
# Create backup directory if needed
[ ! -d "$backup_dir" ] && mkdir -p "$backup_dir"
# Check if source exists
if [ ! -d "$source_dir" ]; then
echo "ERROR: Source directory not found"
exit 1
fi
# Perform backup
tar -czf "$backup_dir/backup.tar.gz" "$source_dir"
echo "Backup complete"
Check if Directory is Empty
dir="/some/directory"
if [ -d "$dir" ] && [ -z "$(ls -A "$dir")" ]; then
echo "Directory is empty"
fi
Find Readable Directories
for dir in /etc /var /home /root; do
if [ -d "$dir" ] && [ -r "$dir" ]; then
echo "Can read: $dir"
fi
done
Key Test Operators
| Operator | Test |
|---|---|
-d | Directory exists |
-r | Directory is readable |
-w | Directory is writable |
-x | Directory is accessible |
Always use quotes: [ -d "$dir" ]