MoonPoint Support Logo

 

Shop Amazon Warehouse Deals - Deep Discounts on Open-box and Used ProductsAmazon Warehouse Deals



Advanced Search
January
Sun Mon Tue Wed Thu Fri Sat
1
       
2017
Months
Jan


Sun, Jan 01, 2017 8:45 pm

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
fi

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
fi

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.

[ More Info ]

[/os/unix/bash] permanent link

Valid HTML 4.01 Transitional

Privacy Policy   Contact

Blosxom logo