check if directory exists shell script

How to Check if Directory Exists in Shell Script

Sometimes you may need to check if directory exists in shell script. In this article, we will learn how to find out if a given folder exists or not, using shell script. You can use these commands on all shells, in almost every Linux distributions.

How to Check if Directory Exists in Shell Script

It is very easy to check if a directory exists in shell script. Let us say you want to check if folder /home/data exists. Here is the code to do so.

if [ -d "$DIRECTORY" ]; then
  # code to be executed if $DIRECTORY exists.

In the above if condition, we use -d operator to check if a given directory exists or not.

Similarly, here is the code to check if directory doesn’t exist. In this case, we simply use a negation operator before -d operator to check if the directory does not exist.

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

But please note, the above conditions work for symbolic links as well. So if you check a symlink with -d operator, it will treat the symlink as a folder, as shown below.

if [ -d "$SYMLINK" ]; then 
  rmdir "$SYMLINK" 

Running the above code, will give the following error.

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

This is because the if condition evaluates to True even for symlinks but the rmdir command works for directories only, and not symlinks.

In such cases, we need to use -L operator to check if the given folder is actual directory or symlink.

if [ -d "$LINK_OR_DIR" ]; then 
  if [ -L "$LINK_OR_DIR" ]; then

    # Symbolic link specific commands go here.
    rm "$LINK_OR_DIR"

    # Directory specific command goes here.
    rmdir "$LINK_OR_DIR"

In the above code we use nested if-else statements. The outer if statement uses -d operator to check if the given location is directory or symlink. If it is either of them, then the condition evaluates to True. The inner if-else condition uses -L operator to check if it is a symlink. If the inner if condition evaluates to True, then code related to symlinks is executed, else code related to directories is executed.

In this article, we have learnt how to check if a folder exists or not in shell script. You can run these commands in shell terminal as well as shell scripts.

Also read:

How to Check if Directory Exists in Python
How to Get Directory of Shell Script
How to Create Multiline String in Python
How to Disable SSH Password Authentication
How to Kill Process Running Longer Than Specific Time

Leave a Reply

Your email address will not be published. Required fields are marked *