How to check if a directory exists in a bash script?
How to check if a directory exists in a bash script?
In shell script implementation you might come across use case where you need to perform some operation in a directory, but what if directory is not present then your script might break. To avoid the failure and display user friendly error, we should validate if directory is exists or not in bash shell script.
Check if directory is exists
DIRECTORY=/tmp/users
if [ -d "$DIRECTORY" ]; then
echo "Directory is exists"
fi
Check if directory is not exists
DIRECTORY=/tmp/users
if [ ! -d "$DIRECTORY" ]; then
echo "Directory is not exists"
fi
Above check doesn’t work if symbolic link to a directory. You can one more condition to check the directory exists or not and later you can check if director is symbolic link.
SYMLINK_OR_DIR=/path/to/DIR/or/SYMLINK
if [ -d "$SYMLINK_OR_DIR" ]; then
if [ -L "$SYMLINK_OR_DIR" ]; then
echo "It's Symbolic Link."
else
echo "It's a directory."
fi
fi
(Visited 317 times, 6 visits today)