How To Check If a Directory Exists In a Shell Script

You can check if a directory exists in a shell script by using the if statement in combination with the test command or the [ command.

For example, using the test command:

if [ -d "/path/to/directory" ]; then
echo "Directory exists"
else
echo "Directory does not exist"
fi

Using the [ command:

if [ -d "/path/to/directory" ]
then
echo "Directory exists"
else
echo "Directory does not exist"
fi

In both examples, the -d option is used to test for the existence of a directory. The if statement evaluates the result of the test or [ command and prints a message depending on whether the directory exists or not.

Leave a Comment