Bash scripts often need to interact with the file system, and a common task is to verify whether a directory exists before attempting to read from or write to it. This tutorial will guide you through different methods for checking directory existence in your Bash scripts, including handling symbolic links.
Basic Directory Existence Check
The primary way to check if a directory exists is by using the -d
test operator within a conditional statement (if
). The basic structure is:
if [ -d "$DIRECTORY" ]; then
# Code to execute if the directory exists
echo "$DIRECTORY exists."
fi
Here, $DIRECTORY
is a variable holding the path to the directory you want to check. The -d
operator returns true if the path exists and is a directory. The if
statement then executes the code block within it.
Important: Quoting Variables
Always enclose your variables in double quotes ("$DIRECTORY"
) when using them in conditional expressions. This is crucial for handling directory names that contain spaces or other special characters. Without quotes, the shell might interpret the spaces as separators, leading to incorrect results or errors.
if [ -d "$DIRECTORY WITH SPACES" ]; then
echo "Directory with spaces exists."
fi
Handling Symbolic Links
A potential pitfall is that the -d
test also returns true for symbolic links pointing to directories. If your script needs to differentiate between an actual directory and a symbolic link, you must add an additional check.
Use the -L
operator to determine if a path is a symbolic link. Here’s how you can combine the checks:
if [ -d "$LINK_OR_DIR" ]; then
if [ -L "$LINK_OR_DIR" ]; then
# It's a symbolic link!
echo "$LINK_OR_DIR is a symbolic link."
# Perform actions specific to symbolic links
else
# It's a directory!
echo "$LINK_OR_DIR is a directory."
# Perform actions specific to directories
fi
fi
This code first checks if the path exists and is a directory or a symbolic link pointing to one. If it is, it then checks if it’s a symbolic link. Based on the result, you can execute the appropriate code block.
Using [[ ]]
for More Readable Conditions
The [[ ]]
compound command provides a more flexible and readable way to write conditional expressions. It avoids some of the quoting pitfalls of the [ ]
command and allows for more complex conditions.
if [[ -d "$DIRECTORY" && ! -L "$DIRECTORY" ]]; then
echo "It's a bona-fide directory."
fi
This example uses &&
(logical AND) and !
(logical NOT) to check if the path is a directory and is not a symbolic link.
Shorthand Notation
For simple checks, you can also use a shorthand notation:
[ -d "$DIR" ] && echo "Yes"
This will print "Yes" to the console if the directory exists.
By understanding these methods and considering the potential for symbolic links, you can reliably check for directory existence in your Bash scripts and ensure that your code behaves as expected.