How to check if directory exists or not using shell script

In some cases, we wants to check whether the directory is exists or not using shell script.If the directory exists, we might remove the existing one or creating the file under the directory.

-d operator in bash

-d is a operator to test if the given directory is exists or not.

We can check whether the directory exists or not using the above if condition with -d operator. It will be TRUE only if the directory is exists.

Check if a directory exists

Here we are checking the directory /etc/revisit/test is exists using -d $directory expression.

Check if a directory doesn’t exists

Here ! means not and -d means test if directory exists. The if condition will be TRUE only if the directory doesn’t exists.

Check whether the directory is exists or not

The above code will help you to check whether the directory is exists or not and you can perform any other operation within the if and else statements.

Using test command to check whether the directory exists or not

Test command is another way of checking the directory exists or not. The new upgraded version of the test command [[ (double brackets) is supported on most modern systems using Bash, Zsh, and Ksh as a default shell.

Recommended Articles