DebugPointer
Published on

How to check if a directory exists in a Bash Script?

How to check if a directory exists in a Bash Script?

Checking if a directory exists or not can be easily done with the script below

if [ -d "$DIRECTORY_PATH" ]; then
  # If the $DIRECTORY_PATH exists, code inside the block will get executed
fi

Or to check if a directory doesn't exist:

if [ ! -d "$DIRECTORY_PATH" ]; then
  # If the $DIRECTORY_PATH does not exists, code inside the block will get executed
fi

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.