In this tutorial, the Bash script checks whether a directory exists or not.

Bash scripting Check if directory exists

In this example,

if then the block is used to test conditional expression of directory

Let us see some examples.

-check directory exists and print message. The conditional expression contains the -d option and directory path. -d option which checks for 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, used if-else conditional block

  • Checked if directory exists using -d.
  • else block will have a code for not exists 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 uses in place of if conditional expressions.

Here is an example conditional expression

FOLDER=test
[ -d "$folder" ] && echo "folder exists" || echo "folder not exist"
  • Check multiple directories exists Sometimes, We want to check 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 exists"
fi

Check directory exists and writable and executable

In this example, Code checks for below things

  • folder exists or not
  • if exists, the Folder has permission to write and executable.
  • Finally, Print 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 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