Check if a directory exists in a shell script

Use the following conditions to check if a “directory exists” in a shell script

if [ -d $DIRECTORY ]
then
rm -rf $DIRECTORY
fi

or

if [ ! -d $DIRECTORY ]
then
mkdir $DIRECTORY

Test case: Assume “testdir” is the file to check. The below script will check the file and if it exists, remove it or else create it.

#!/bin/bash

if [ -d testdir ]; then
 rm -rf testdir
else
 mkdir testdir
fi

For more if switches: http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_01.html


Leave a comment