How to Check if Directory Exists in Bash Script
In bash, you can check if a directory exists using the
if [ -d "directory_path" ] test. This condition returns true if the specified directory exists, allowing you to run commands based on that check.Syntax
The basic syntax to check if a directory exists in bash is:
if [ -d "directory_path" ]: Tests if the directory exists.then: Starts the block of commands to run if the test is true.else: (Optional) Runs commands if the directory does not exist.fi: Ends the if statement.
bash
if [ -d "directory_path" ]; then # commands if directory exists else # commands if directory does not exist fi
Example
This example checks if the directory /tmp/myfolder exists and prints a message accordingly.
bash
#!/bin/bash DIR="/tmp/myfolder" if [ -d "$DIR" ]; then echo "Directory $DIR exists." else echo "Directory $DIR does not exist." fi
Output
Directory /tmp/myfolder does not exist.
Common Pitfalls
Common mistakes when checking directories include:
- Using
-finstead of-d, which checks for files, not directories. - Not quoting the directory path, which can cause errors if the path contains spaces.
- Using single brackets
[ ]without spaces around the brackets and operators.
bash
Wrong way (checks for file, not directory): if [ -f "$DIR" ]; then echo "This is a file, not a directory." fi Right way: if [ -d "$DIR" ]; then echo "This is a directory." fi
Quick Reference
| Test Option | Description |
|---|---|
| -d | True if the directory exists |
| -f | True if the file exists and is a regular file |
| -e | True if the file or directory exists (any type) |
Key Takeaways
Use
[ -d "directory_path" ] to check if a directory exists in bash.Always quote directory paths to handle spaces correctly.
Do not confuse
-d (directory) with -f (file).Use
if statements to run commands conditionally based on directory existence.Remember to include spaces around brackets and operators in bash tests.