Check if directory exists

To check if a directory exists is quite easy in shell scripts. We have written our own backup script and within the script we use the following code:

if [ ! -d "/var/www/backups/$(date +%Y%m%d)" ]; then echo "making directory /var/www/backups/$(date +%Y%m%d)\n" mkdir /var/www/backups/$(date +%Y%m%d) fi

The -d asks the question, is the following a directory and the exclamation mark ! says not. In reading terms it says, if this is not a directory then.

Once we know that it is not a directory, we can create the directory with our mkdir statement.