How to check that if a directory exists in a Bash shell script?

· · 3260 views

In my shell script, I need to check if a directory exists or not. So, here what command I should use to verify a directory exist or not in a given path?

0
2 Answers

To check if a directory exists in a shell script:

if [ -d "$DIRECTORY" ]; then
  # Control will enter here if $DIRECTORY exists.
fi

Or to check if a directory doesn't exist:

if [ ! -d "$DIRECTORY" ]; then
  # Control will enter here if $DIRECTORY doesn't exist.
fi

However, subsequent commands may not fill in as proposed if you don't consider that a symbolic link to a directory will also pass this check. For example, running this:

ln -s "$ACTUAL_DIR" "$SYMLINK"
if [ -d "$SYMLINK" ]; then 
  rmdir "$SYMLINK" 
fi

Will produce the error message:

rmdir: failed to remove `symlink': Not a directory

So symbolic links may have to be treated differently if subsequent commands expect directories:

if [ -d "$LINK_OR_DIR" ]; then 
  if [ -L "$LINK_OR_DIR" ]; then
    # It is a symlink!
    # Symbolic link specific commands go here.
    rm "$LINK_OR_DIR"
  else
    # It's a directory!
    # Directory command goes here.
    rmdir "$LINK_OR_DIR"
  fi
fi
0

You can use -d with if condition to check if a directory exists or not:

if [ -d $DIRECTORY ]; then
  # $DIRECTORY exists.
fi

Make sure to wrap factors by double-quotes while referring to them in a Bash script. Because if $DIRECTORY has spaces or special-characters then your script will blow up. You don't want that. So use this.

if [ -d "$DIRECTORY" ]; then
    # Will enter here if $DIRECTORY exists, even if it contains spaces
fi

With the same syntax you can use:

-e: any kind of archive
-f: file
-h: symbolic link
-r: readable file
-w: writable file
-x: executable file
-s: file size greater than zero
0

Please login or create new account to participate in this conversation.