Skip to content
Home » Shell Script » Check if Directory Exists by Shell Script

Check if Directory Exists by Shell Script

Test Command

In some situations, we may need to detect the existence of a directory in shell or scripts. If so, there's a quick way to test it.

Here we use a set of conditional expressions in shell script to determine the existence of a directory and then return a definite result. The shell command is as below:

[ -d "/path/to/be/tested" ] && echo "The directory DOES exist." || echo "The directory does NOT exist."

In the entire command, && is a logical AND operator in short-circuit form, whereas || is a logical OR operator.

This is how it works:

  • The first part is an expression of command test, argument -d is responsible for detecting the existence of a directory.
  • If the first test returns TRUE, then it makes sure the second part will be executed in order to get TRUE and ignore the rest of evaluations.
  • If the first test returns FALSE, then there's no need to evaluate the second part and the third part will be executed in order to get TRUE.

Let's see how we use it.

Valid Directory

We input a valid path in the command to get the result.

[oracle@test ~]$ [ -d "/u01/app/oracle/product/19.3.0/db_1" ] && echo "The directory DOES exist." || echo "The directory does NOT exist."
The directory DOES exist.

The result clearly says the path is existing.

Invalid Directory

We input an invalid path in the command to get the result.

[oracle@test ~]$ [ -d "/No/such/file/or/directory" ] && echo "The directory DOES exist." || echo "The directory does NOT exist."
The directory does NOT exist.

The result clearly says the path is not existing.

The testing command in the above can be used in Bash (Linux) and KSH (AIX, Solaris), you may modify the echo string for your own use.

Leave a Reply

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