0

I was reading this answer by @dessert: https://askubuntu.com/a/990771/853133 about how to delete old backup folders from directory using cron in Ubuntu. The command given was:

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

However, CentOs 7 doesn't like the z flag in his call to head:

head: invalid option -- 'z'

Is there a work-around for CentOs7?

I took a look at: How can I execute an equivalent of `head -z` when I don't have the `-z` option available? I don't think this explanation is applicable to my question. I don't see how I would change my command if I want to delete backups older than n.

  • Is it important that you specifically keep the last six backups, or do you just want to remove backups older than a certain threshold? If age is the key, you could just use find [...] -delete. – DopeGhoti Sep 18 '18 at 18:58
  • @DopeGhoti: My preference is just the last n backups... – random_dsp_guy Sep 18 '18 at 19:13

1 Answers1

1

Yes, support for NUL-delimited records has being added gradually to GNU utilities over the past few decades. GNU head -z is relatively recent (2015), while GNU sort has had -z for decades (1996) and xargs -0 even longer (1990).

Here, you could also do:

find /BACKUPDIR/ -mindepth 1 -maxdepth 1 -type d -print0 |
  sort -rz | sed -z 1,6d | xargs -r0 echo rm -rf

The -z addition to GNU sed is recent (2012), not as recent as head's.

GNU text utilities have been able to cope with NUL bytes in their input for decades, so you can always do:

find /BACKUPDIR/ -mindepth 1 -maxdepth 1 -type d -print0 |
  tr '\0\n' '\n\0' |
  sort -r | tail -n +7 | 
  tr '\0\n' '\n\0' |
  xargs -r0 echo rm -rf

Or you can always install zsh and do

echo rm -rf /BACKUPDIR/*(D/[1,-7])

(see also it's n glob qualifier to sort numerically so 10 sorts after 9 instead of between 1 and 2).

(dates above are from ChangeLogs, the official releases where those changes were included may have come a little later).