How to check if a directory exist in a Bash Script?
A directory consists of files or sub-directories. While programming or writing a Bash script, you'll often come across a situation where you have to check if a directory exists in a certain path. Depending on the existence of a directory, you usually end up doing a certain logic or operation.
So, let's see how we can check if the directory exists in a path or not.
Check if Directory exist in Bash Script
Checking if a directory exist or not can be easily done by using if
command. if
performs a conditional check on the command that goes inside the brackets [ ]
.
if [ -d "$DIRECTORY_PATH" ]; then
# If the $DIRECTORY_PATH exist, code inside the block will get executed
fi
Check if Directory does not exist in Bash
Here we are checking the error condition or the negative condition if the directory does not exist.
if [ ! -d "$DIRECTORY_PATH" ]; then
# If the $DIRECTORY_PATH does not exist, code inside the block will get executed
fi
Are you looking for the scenario if a file exist or not in bash scripts?
Note that a the code inside the if
block will still get executed if the folder was a symbolic link.
Also Note that, the "$DIRECTORY_PATH"
is enclosed with double quotes. This is to handle cases where the directory name can have spaces and special characters(wildcard characters).
Let's say you had created a symbolic link of a folder.
ln -s "$DIRECTORY_PATH" "$SYMLINK_PATH"
Now if we check if the symbolic link, you will get an error rmdir: failed to remove 'symlink': Not a directory
if [ -d "$SYMLINK_PATH" ]; then
rmdir "$SYMLINK_PATH"
fi
So, to treat this edge case, we will have to handle symlink's condition as shown below.
if [ -d "$DIRECTORY_PATH" ]; then
if [ -L "$DIRECTORY_PATH" ]; then
# It is a symlink!
# Symbolic link specific commands go here.
rm "$DIRECTORY_PATH"
else
# It's a directory!
# Directory command goes here.
rmdir "$DIRECTORY_PATH"
fi
fi
The above code is an ideal way to check if a path is a directory or not.