How to check if directory exists or not using shell script
Contents
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.
1 |
if [ -d $directory ] |
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
1 2 3 4 |
Dir=/etc/revisit/test if [ -d $Dir ]; then echo "Directory exists" fi |
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.
1 2 3 4 |
Dir=/etc/revisit/test1 if [ ! -d $Dir ]; then echo "Directory doesn't exists" fi |
Check whether the directory is exists or not
1 2 3 4 5 6 |
Dir=/etc/revisit/test if [ -d $Dir ]; then echo "Directory exists" else echo "Directory doesn't exists" fi |
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.
1 2 3 4 5 6 7 |
Dir=/etc/revisit/test if test -d "$Dir" then echo "Directory exists" else echo "Directory doesn't exists" fi |
Recommended Articles