Checking if a directory exists is one of the most fundamental tasks in Bash scripting. In real terms, whether you are writing a simple backup script, automating a deployment pipeline, or building a complex system administration tool, verifying the presence of a folder before attempting to read, write, or modify it prevents errors and ensures your logic flows correctly. The Bash shell provides several built-in mechanisms to perform this check, primarily centered around the test command and its syntactic sugar, the double brackets [[ ]].
The Standard Approach: Using -d with Double Brackets
The most idiomatic and solid way to check for a directory in modern Bash is using the -d operator inside double square brackets [[ ]]. This construct is a Bash keyword (not an external command), offering better performance and safer handling of variables containing spaces or special characters And that's really what it comes down to..
#!/bin/bash
DIRECTORY="/path/to/your/directory"
if [[ -d "$DIRECTORY" ]]; then
echo "Directory exists: $DIRECTORY"
else
echo "Directory does not exist: $DIRECTORY"
fi
Key details to remember:
- Quote your variables: Always wrap
$DIRECTORYin double quotes ("$DIRECTORY"). Without quotes, a path containing spaces (e.g.,/home/user/My Documents) will cause a syntax error because Bash splits the string into multiple arguments. - Symlinks: The
-doperator follows symbolic links. If/path/to/diris a symlink pointing to a real directory,-dreturns true (exit code 0). If the symlink is broken (points to nowhere), it returns false.
The POSIX Compliant Method: Single Brackets [ ]
If you are writing scripts intended to run on strictly POSIX-compliant shells (like dash or /bin/sh on Debian/Ubuntu), you must use single brackets [ ]. This is the portable test command.
if [ -d "$DIRECTORY" ]; then
echo "Directory exists"
fi
Critical differences from [[ ]]:
- Word Splitting: Inside
[ ], unquoted variables undergo word splitting and glob expansion. Quoting is mandatory. - Operators: You cannot use
&&or||inside[ ]; you must use-a(and) and-o(or), though these are deprecated in favor of running multiple[ ]commands. - Globs: Patterns like
*are expanded inside[ ]but not inside[[ ]].
For almost all modern Linux scripting (Bash, Zsh, Ksh), [[ -d ... ]] is preferred.
One-Liners for Quick Checks
In interactive terminals or compact scripts, you often see logical operators (&& and ||) used for inline checks. This leverages the exit status of the test command (0 for success/true, non-zero for failure/false) Not complicated — just consistent. Worth knowing..
Run a command only if the directory exists:
[[ -d "/var/log/nginx" ]] && echo "Nginx logs found"
Run a command only if the directory is missing:
[[ ! -d "/tmp/build" ]] && mkdir -p "/tmp/build"
The classic if/then/else one-liner:
if [[ -d "$HOME/projects" ]]; then cd "$HOME/projects"; else echo "Project folder missing"; fi
Distinguishing Directories from Files and Symlinks
A common pitfall is confusing "exists" with "is a directory". Bash provides distinct operators for different filesystem object types:
| Operator | True If... |
|---|---|
-d |
File exists and is a directory (follows symlinks). |
-e |
File exists (any type: file, directory, socket, pipe, etc.Think about it: ). |
-f |
File exists and is a regular file. |
-L or -h |
File exists and is a symbolic link (does not follow the link). |
Scenario: You want to ensure a path is specifically a directory and not a file.
TARGET="/etc/passwd" # This is a file
if [[ -e "$TARGET" ]]; then
echo "Path exists.In real terms, "
elif [[ -f "$TARGET" ]]; then
echo "It is a regular file. Plus, "
if [[ -d "$TARGET" ]]; then
echo "It is a directory. "
fi
else
echo "Path does not exist.
This changes depending on context. Keep that in mind.
## Handling Symbolic Links Explicitly
Because `-d` follows symlinks, `[[ -d "symlink_to_dir" ]]` returns true. Sometimes you need to know if the *actual object* at the path is a directory, regardless of whether it is a link. Other times, you need to detect the link itself.
The official docs gloss over this. That's a mistake.
**1. Check if it is a directory (resolving links) — Standard `-d`:**
```bash
# Returns true for real dirs AND symlinks pointing to dirs
[[ -d "$PATH" ]]
2. Check if it is a symlink pointing to a directory:
if [[ -L "$PATH" && -d "$PATH" ]]; then
echo "It is a symlink resolving to a directory."
fi
3. Check if the path itself is a directory and not a symlink:
if [[ -d "$PATH" && ! -L "$PATH" ]]; then
echo "It is a physical directory, not a symlink."
fi
4. Check for a broken symlink:
# -L is true (it's a link), but -d/-e are false (target missing)
if [[ -L "$PATH" && ! -e "$PATH" ]]; then
echo "Broken symlink detected."
fi
Creating Directories Only If Missing (Idempotency)
A very common pattern in setup scripts is "ensure this directory exists." The mkdir -p command is idempotent: it creates parent directories as needed and does not throw an error if the directory already exists.
Best Practice (No explicit check needed):
mkdir -p "/var/www/html/project/assets"
This single line replaces:
# Redundant pattern
if [[ ! -d "/var/www/html/project/assets" ]]; then
mkdir -p "/var/www/html/project/assets"
fi
Use the explicit if [[ ! -d ... ]] check only if you need to perform different logic based on whether the directory was just created versus already existing (e.g., setting specific permissions only on creation, or logging a "first run" message) Less friction, more output..
Checking Permissions Alongside Existence
Existence does not imply accessibility. A directory might exist, but your script might lack execute (x) permission to cd into it or read (r) permission to list its contents Small thing, real impact..
Check read, write, and execute permissions:
DIR="/secure/data"
if [[ -d "$DIR" ]]; then
if [[ -r "$DIR" && -w "$DIR" && -x "$DIR" ]]; then
echo "Directory exists and is fully accessible (RWX)."
else
echo "Directory exists but permissions are insufficient."
fi
-r: Read permission (list files). Day to day, *-w: Write permission (create/delete files inside). Still, " # Handle error: maybe run with sudo, or exit gracefully fi else echo "Directory missing. *-x: Execute permission (traverse/enter the directory).
on them Turns out it matters..
Note on -w for directories: Write permission on a directory controls whether you can create or delete entries within it, not whether you can modify existing files. Modifying a file's contents depends on the write permission of the file itself.
Note on root and permissions: If your script runs as root, the -r, -w, and -x tests almost always return true regardless of the actual permission bits, because root bypasses standard permission checks. Don't rely on these tests to validate permissions when running privileged.
Common Pitfalls
Always quote your variables. An unquoted $PATH will break the moment it contains a space or a glob character:
DIR="/path/with spaces/my dir"
[[ -d $DIR ]] # WRONG: word-splitting and globbing wreak havoc
[[ -d "$DIR" ]] # CORRECT: the variable is treated as a single argument
Watch out for the [ vs [[ distinction. The single-bracket [ ] is the POSIX test command and requires spaces around every operator. The double-bracket [[ ]] is a bash keyword with safer parsing and no word-splitting on expansions. Prefer [[ ]] in bash scripts Simple, but easy to overlook. That's the whole idea..
Beware of empty variables. If $DIR is unset or empty, [[ -d "$DIR" ]] evaluates [[ -d "" ]], which is false — usually what you want. But always initialize or validate critical variables before testing them:
DIR="${TARGET_DIR:-}"
if [[ -z "$DIR" ]]; then
echo "Error: TARGET_DIR is not set." >&2
exit 1
fi
~ does not expand inside quotes. The tilde is expanded by the shell before quoting rules apply, so:
DIR="~/backups"
[[ -d "$DIR" ]] # FALSE: looks for a literal "~" directory
DIR=~/backups # TRUE: tilde expands because it's unquoted at assignment
# or, more explicitly:
DIR="$HOME/backups"
A Practical Helper Function
Once you know the building blocks, you can wrap them into a reusable function that makes your scripts read like plain English:
#!/usr/bin/env bash
require_dir() {
local dir="$1"
if [[ ! In real terms, -d "$dir" ]]; then
echo "Error: required directory not found: $dir" >&2
exit 1
fi
if [[ ! -r "$dir" || !
# Usage
require_dir "/etc/myapp"
echo "Proceeding with configuration..."
This fails fast with a clear message rather than letting a missing directory cause confusing errors deep inside your script That alone is useful..
Conclusion
Checking whether a directory exists in bash comes down to a small set of reliable tools. Plus, the -d operator answers "is this a usable directory? " and follows symlinks by default. In real terms, when the distinction between a real directory and a symlink matters, combine it with -L to inspect the link itself, and use -e to detect broken links. For the common "make sure it exists" case, mkdir -p is already idempotent and needs no guard Not complicated — just consistent..
Beyond mere existence, reliable scripts verify that a directory is actually accessible with -r, -w, and -x, since a directory you cannot enter is functionally as good as missing. And throughout, the small habits matter most: quote your variables, prefer [[ ]] over [ ], guard against empty input, and remember that permission tests behave differently under root.
Master these few operators and patterns, and directory handling in your scripts will be both correct and readable — turning a frequent source of subtle bugs into a solved problem Most people skip this — try not to..