I'm trying to get crontab to automatically remove backup folders in a directory apart from the most recent 6 folders as a backup is created in the directory every day.

All my backup folders are just datestamps e.g: 2017_12_29.

When I run rm -rf $(ls -1 /BACKUPDIR/ | head -n -6) from a terminal it deletes all folders except the most recent 6 which is what I expect it to do, but it doesn't seem to do anything when crontab runs it and nothing is deleted from the directory.

I'm not sure where I'm going wrong here.

EDIT: Currently I'm just using rsync to clone the / directory excluding a few directories.

This is what it looks like in root's crontab:

00 22 * * * /usr/bin/rsync -aqvHAXS --exclude /dev/ --exclude /proc/ --exclude /sys/ --exclude /tmp/ --exclude /run/ --exclude /mnt/ --exclude /media/ --exclude /lost+found/ --delete / /BACKUPDIR/$(date +\%Y_\%m_\%d)
  • 1
    It can be a permission problem, does the script under cron run with the appropriate user to be able to delete things in /BACKUPDIR/ ? As a simple debug, put under cron something like ls -1 /BACKUPDIR/ | head -n -6 > /tmp/debug 2>&1 and see what appears in /tmp/debug. Also, if not already, have a look at rsnapshot tool it handles all things for you automatically. Dec 29, 2017 at 22:59
  • 1
    Can you update your question with your script, your crontab setup and permissions for both? Dec 30, 2017 at 0:33
  • I've added the script now as an edit, the scripts are all running from root's crontab.
    – Jakoski360
    Dec 30, 2017 at 13:31

1 Answer 1


Parsing ls is not a good idea at all, so here's a solution I consider more stable:

find /BACKUPDIR/ -mindepth 1 -maxdepth 1 -type d -print0 | sort -z | head -zn-6 | xargs -0 echo rm -rf

This just prints the rm command for testing purposes, if it does what you want remove echo and simply add it to your crontab, e.g. to run every Sunday at 18:00:

00 18 * * 0 find /BACKUPDIR/ -mindepth 1 -maxdepth 1 -type d -print0 | sort -z | head -zn-6 | xargs -0 rm -rf
  • Permissions might still be the problem if it is e.g. not the root's crontab but the users'.
    – derHugo
    Dec 30, 2017 at 12:18
  • @derHugo OP executes rm -rf from a terminal and it works – I take that as a sign permissions are not a problem here.
    – dessert
    Dec 30, 2017 at 12:24
  • I've just added this into root's crontab now and it's worked perfectly, I see where I was going wrong before by parsing ls. Marked as correct answer thanks for the help.
    – Jakoski360
    Dec 30, 2017 at 13:40
  • @dessert what's the reason for head -zn-6 ? Sep 18, 2018 at 17:54
  • @Seth This spares the six most recent folders as requested in the question.
    – dessert
    Sep 18, 2018 at 17:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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