Bash: How to Check if Directory Exists
The Problem
Need to check if a directory exists before doing something with it? Here’s how to do it properly in Bash!
Basic Directory Check
#!/bin/bash
test_dir_exist(){
set -e
if [ -e "/home/jayleekr/workspace/00_codes/05_info_archive" ]; then
echo "DIR Exist"
exit 1
fi
}
test_fail(){
echo "test_fail"
}
test_dir_exist
Running this:
$ ./directory_ex.sh
DIR Exist
Better Approaches
1. Using -d for Directory-Specific Check
#!/bin/bash
check_directory() {
local dir_path="$1"
if [ -d "$dir_path" ]; then
echo "✅ Directory '$dir_path' exists"
return 0
else
echo "❌ Directory '$dir_path' does not exist"
return 1
fi
}
# Usage
check_directory "/home/user/workspace"
2. Create Directory if It Doesn’t Exist
#!/bin/bash
ensure_directory() {
local dir_path="$1"
if [ ! -d "$dir_path" ]; then
echo "Creating directory: $dir_path"
mkdir -p "$dir_path"
else
echo "Directory already exists: $dir_path"
fi
}
# Usage
ensure_directory "/tmp/my_project/logs"
3. Multiple Directory Checks
#!/bin/bash
check_multiple_dirs() {
local dirs=("$@")
local all_exist=true
for dir in "${dirs[@]}"; do
if [ ! -d "$dir" ]; then
echo "❌ Missing: $dir"
all_exist=false
else
echo "✅ Found: $dir"
fi
done
if [ "$all_exist" = true ]; then
echo "🎉 All directories exist!"
return 0
else
echo "💥 Some directories are missing!"
return 1
fi
}
# Usage
check_multiple_dirs "/tmp" "/home" "/var/log" "/nonexistent"
Different Test Operators
Here are the different ways to test for files and directories:
# -e: exists (file or directory)
[ -e "/path" ] && echo "Something exists at /path"
# -f: regular file exists
[ -f "/path/file.txt" ] && echo "File exists"
# -d: directory exists
[ -d "/path/dir" ] && echo "Directory exists"
# -r: readable
[ -r "/path" ] && echo "Readable"
# -w: writable
[ -w "/path" ] && echo "Writable"
# -x: executable
[ -x "/path" ] && echo "Executable"
Practical Examples
1. Backup Script
#!/bin/bash
BACKUP_DIR="/backup/$(date +%Y%m%d)"
if [ ! -d "$BACKUP_DIR" ]; then
echo "Creating backup directory: $BACKUP_DIR"
mkdir -p "$BACKUP_DIR"
fi
echo "Backing up to: $BACKUP_DIR"
# Your backup commands here...
2. Project Setup
#!/bin/bash
setup_project() {
local project_name="$1"
local project_dirs=("$project_name/src" "$project_name/tests" "$project_name/docs")
for dir in "${project_dirs[@]}"; do
if [ ! -d "$dir" ]; then
echo "Creating: $dir"
mkdir -p "$dir"
fi
done
echo "Project structure created for: $project_name"
}
# Usage
setup_project "my_awesome_app"
3. Log Rotation Check
#!/bin/bash
LOG_DIR="/var/log/myapp"
ARCHIVE_DIR="/var/log/myapp/archive"
if [ -d "$LOG_DIR" ]; then
echo "Log directory exists"
# Create archive directory if needed
[ ! -d "$ARCHIVE_DIR" ] && mkdir -p "$ARCHIVE_DIR"
# Rotate logs
find "$LOG_DIR" -name "*.log" -mtime +7 -exec mv {} "$ARCHIVE_DIR" \;
else
echo "Log directory not found: $LOG_DIR"
exit 1
fi
Pro Tips
- Always quote variables:
[ -d "$dir" ]
not[ -d $dir ]
- Use -d for directories: More specific than -e
- Handle spaces in paths: Quoting protects against spaces
- Exit codes matter: Return meaningful exit codes for scripting
- Create parent directories: Use
mkdir -p
to create nested directories
Common Pitfalls
# ❌ Don't do this
if [ -d $HOME/my dir ]; then # Breaks with spaces!
# ✅ Do this instead
if [ -d "$HOME/my dir" ]; then # Properly quoted
# ❌ Don't do this
if [ -e "$dir" ]; then # Could be a file!
# ✅ Do this for directories
if [ -d "$dir" ]; then # Specifically checks for directory
References
- General: Bash Beginners Guide
- Test operators:
man test
orhelp test
Directory checks are fundamental - get them right and your scripts will be much more robust! 🚀
Share this article
Found this helpful? Share it with your network
관련 글
Join the Discussion
Share your thoughts and connect with other readers
댓글
GitHub 계정으로 로그인하여 댓글을 남겨보세요. 건설적인 의견과 질문을 환영합니다!
댓글을 불러오는 중...
댓글을 불러올 수 없습니다.