In this tutorial, we’ll explore how to determine whether a directory exists in a Bash script.

Bash scripting Check if the directory exists

In the examples below, the if block is used to test the conditional expression for the existence of a directory.

Check if a Directory Exists and Print a Message

The conditional expression uses the -d option to check if the directory exists.

-check directory exists and prints the message. The conditional expression contains the -d option and directory path. -d option which checks for a directory exists or not.

Here is an example

FOLDER=test

if [ -d "$FOLDER" ]; then
    echo "Directory Exists"
fi

Please note that add space after [ and before -d.

  • How to mkdir only if a directory does not already exist?

In this example, using an if-else conditional block.

  • Checked if the directory exists using -d.
  • else block will have a code for not existing and create a directory using the directory path

Here is a code

FOLDER=test

if [ -d "$FOLDER" ]; then
    echo "Directory Exists"
else
    echo "Directory Exists"
    mkdir "$FOLDER"
fi

-Check directory exists using ternary syntax

Alternatively, the ternary conditional expression is used in place of if conditional expressions.

Here is an example conditional expression

FOLDER=test
[ -d "$folder" ] && echo "folder exists" || echo "folder not exist"
  • Check if multiple directories exist Sometimes, We want to check that multiple directories exist.

We have to use if conditional statements with logical AND operator(&&).

FOLDER1=test1
FOLDER2=test2

if [ -d "$FOLDER1" ] && [ -d "$FOLDER2" ] then
   echo "Folder1 and Folder2 exist"
fi

Check directory exists and is writable and executable

In this example, Code checks for the below things

  • folder exists or not
  • if exists, the Folder has permission to write and executable.
  • Finally, Print a string message
FOLDER=test

if [ -d "$FOLDER" -a -w -x "$FOLDER" ]
then
    echo "Directory exists, writable and executable"
fi

Check files or directory exists

Sometimes, we want to check if the file or directory exists. -e option checks for file or directory for the given path exists or not.

FILE_DIRECTORY=test
if [ -e "$FILE_DIRECTORY" ]
then
    echo "file or directory of test exists."
fi