Check if Directory exist in Bash
Checking if a directory exist or not can be easily done with the script below
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
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.