Facebooktwitterredditpinterestlinkedintumblr

If you write scripts in a Bash shell, you will eventually come across a need to check the existence of a directory. You may want to know if the directory exists before you start writing a file to it. You may want to know if a directory exists before automating some process that reads from that directory.

Whatever the reason, this is a useful command that you should know. To do so, use the IF-THEN statement to perform the verification.

To check if a directory exists in a Bash shell script, add the command below to your script:

if [[ -d "${DIRECTORY}" ]]; then
  echo "Directory exists."
else
  echo "Directory does not exist."
fi

Variable DIRECTORY can be any directory such as /usr/bin, /var/log or /tmp.

You can also do the reverse if you just want to make sure a particular directory doesn’t exist.

if [[ ! -d "${DIRECTORY}" ]]; then
  echo "Directory does not exist."
fi

The exclamation point before the -d option performs the inverse of the task you want to perform. In this case, instead of checking if the directory exists, it’s to check if the directory doesn’t exist.

If you have a symbolic link to a directory, the statements above will also consider it to be a directory. If this is not what you want, you can ignore the symbolic link to a directory by checking for the symbolic link.

if [[ -d "${DIRECTORY}" ]]; then
  if [[ ! -L "${DIRECTORY}" ]]; then
    echo "Directory exists."
  fi
fi

To condense the IF-THEN statements, you can combine them together.

if [[ -d "${DIRECTORY}" && ! -L "${DIRECTORY}" ]]; then
  echo "Directory exists"
fi

The statements above checks if the directory exists and if the directory is not a symbolic link. If both statements are true, then it will proceed running the echo statement.

Leave a Comment