Hello, fellow coders! It’s common to find ourselves in situations where we need to check if a directory exists while running a Bash script. Maybe we need to avoid overwriting data, or perhaps we’re trying to make sure some output directory is ready. Whatever the reason, being able to do this check is a crucial skill. That’s why in this blog post, I’m going to guide you through the process of checking if a directory exists in a Bash script. So, without further ado, let’s get scripting!
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 Folder 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 Folder 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.
And there you have it! You’ve just learned how to check if a directory exists in a Bash script. It’s a straightforward yet powerful tool to have in your arsenal, which could be the difference between a successful script execution and a frustrating error. So go ahead, implement this new skill in your scripts, and take your Bash scripting to the next level. Stay tuned for more tips and tricks on mastering Bash scripting!