Determining if a directory exists in a Bash script

I have a Bash script that copies the prior day's mail log file from /var/log/maillog.1 to another directory for archiving. The archive directory contains a subdirectory for each year's mail logs. Today is the first day of a new year, so I needed to create a 2017 directory. I could manually create the directory, but I thought I'd modify the Bash script that runs from Cron to check on whether the current year's directory exists and, if it doesn't create it, so, if I forget in future years to create a new year's directory the script will create it for me.

You can check if a directory exists with code similar to what is shown below:

if [ -d "$DIRECTORY" ]; then
  # Insert code to be executed

Or, to check if a directory doesn't exist and execute commands if it doesn't:

if [ ! -d "$DIRECTORY" ]; then
  # Insert code to be executed

Note: putting the $DIRECTORY variable in double quotes allows for cases where the directory name may contain a space. Though that won't be the case for my yearly subdirectories, it is something you can allow for by enclosing the variable name in double quotes.

I put the following code in my copy-maillog-daily Bash script to create a copy of yesterday's maillog file in the /root/Documents/logs/maillog/$year subdirectory:

# Copy each days maillog file to an archive directory

year=$(date --date=yesterday +%Y)

# Check on whether the directory for the current year exists and, if it doesn't,
# create it.
if [ ! -d /root/Documents/logs/maillog/"$year" ]; then
   mkdir /root/Documents/logs/maillog/$year

cp -a /var/log/maillog.1 /root/Documents/sysinfo/logs/maillog/$year/maillog.$(date --date=yesterday +%m%d%y)

The script is made executable with chmod u+x copy-maillog-daily and is run each day with the following crontab entry which will be run at 5 minutes after midnight each day:

5 0 * * * /root/bin/copy-maillog-daily 1>/dev/null 2>/dev/null

Note: the crontab file for the account under which the command is run can be edited with the crontab utility using crontab -e.

Related articles:

  1. Daily Rotation of Mail Logs
    Date: September 17, 2004