Ask Ubuntu is a question and answer site for Ubuntu users and developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Every 3 hours the script will run and backup a folder "SOURCE" and it will save it along with the other backups of the current day in the folder "month-day-year" e.g. "03-24-13". When a new day comes, it creates a new folder with the new date and deletes all but the latest backup in the previous day's folder. Here is where the problem is, will not delete the old folders from the previous day. Any ideas why?


DATE=$(date +"%m-%d-%Y")
YESTERDAY=$(date -d '1 day ago' +"%m-%d-%Y")
TIME=$(date +"%T")
SPACE=$(df -P $DIR | tail -1 | awk '{print $4}')
NEEDED=$(du -s $SOURCE | awk '{print $1}')
FOLDERS=$(find $DIR/* -maxdepth 0 -type d | wc -l)

# If there is not enough space, delete the oldest folder
if [ $NEEDED -ge $SPACE ]; then
  ls -dt $DIR/* | tail -n +$FOLDERS | xargs rm -rf

# If there is not a folder for today, create one
if [ ! -d "$DIR/$DATE" ]; then
  mkdir $DIR/$DATE

  # If there is a folder from yesterday, keep only one of its backups
  if [ ! -d "$DIR/$YESTERDAY" ]; then
    ls -dt $DIR/$YESTERDAY/* | tail -n +2 | xargs rm -rf


# Create the new backup directory
if [ ! -d "$DESTINATION" ]; then

# Backup source to destination
share|improve this question
up vote 7 down vote accepted
if [ ! -d "$DIR/$YESTERDAY" ]; then

This one fails to execute. You are testing if there is NOT a directory.

It should be

if [ -d "$DIR/$YESTERDAY" ]; then
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.