To check if a directory exists in a Bash script, you can use the -d
test operator in a conditional statement. Here’s how to do it:
Basic Syntax
if [ -d "/path/to/directory" ]; then
echo "Directory exists."
else
echo "Directory does not exist."
fi
Key Components
-d
: Checks if the path exists and is a directory.- Quotes: Use
" "
around paths with spaces (e.g.,"/path/with spaces"
). - Variables: Use variables to make paths dynamic:
dir="/path/to/directory"
if [ -d "$dir" ]; then
echo "$dir exists."
fi
Common Use Cases
1. Create a Directory If It Doesn’t Exist
dir="/path/to/directory"
if [ ! -d "$dir" ]; then
mkdir -p "$dir"
echo "Created $dir"
fi
!
negates the condition (checks for non-existence).mkdir -p
creates parent directories if needed.
2. Check Multiple Directories
directories=("/etc" "/invalid/path" "/tmp")
for dir in "${directories[@]}"; do
if [ -d "$dir" ]; then
echo "$dir ✔️"
else
echo "$dir ❌"
fi
done
3. Handle Symlinks
To check if a path is a directory and not a symlink:
if [ -d "/path" ] && [ ! -L "/path" ]; then
echo "Real directory (not a symlink)."
fi
-L
checks if the path is a symbolic link.
Edge Cases & Notes
- Spaces in Paths: Always quote variables/paths to handle spaces:
# Bad (fails for paths with spaces):
if [ -d $dir ]; then ...
# Good:
if [ -d "$dir" ]; then ...
- Permissions: The script needs execute permission on the directory’s parent to check existence.
- Empty Variable: If
dir
is unset,[ -d "$dir" ]
returnsfalse
.
Alternative: test
Command
The test
command is equivalent to [ ]
:
test -d "/path/to/dir" && echo "Exists" || echo "Does not exist"
Example Output
$ ./check_dir.sh
Directory /etc ✔️
Directory /invalid/path ❌
Let me know if you need further refinements!