0

Im truly sorry for this horrible title, it's the best I could phrase it.

So I have a backup scripts that creates backup tars of some server data and stores it in /server/backups, however I only need backups of the last week, therefore I created this script to run as a weekly task and clean up my backups folder:

#!/bin/bash
#initializing a with the amount of backup archives and b with the target max
a=find /server/backups/ -type f | wc -l
b=14

#if there are more backup files than target max
#delete the oldest files
if [ $a > $b ]
then
    ls -1t /server/backups/ | tail -n +15 | xargs rm -f
fi  

but it doesn't work. Im very new to linux and i dont know how to "debug" this.

1 Answers1

1
a=find /server/backups/ -type f | wc -l

This runs the command /server/backups/ with the environment variable a set to find. Or actually it probably just gives an error because of the trailing slash. What you want is a command substitution.

if [ $a > $b ]

The > here is a string comparison, so e.g. 2 would be greater than 14. And you should quote the variables, but that's probably not an issue if they just hold numbers.

ls -1t /server/backups/ | tail -n +15 | xargs rm -f

Here, there's the obvious problems with filenames containing whitespace, quotes or newlines (because of how xargs interprets its input by default, and because tail deals with lines). But if we can disregard that, if your filenames are "nice", and you have GNU xargs, then you could just run

ls -t /server/backups/ | tail -n +15 | xargs -d '\n' -r rm

because the output from tail will be empty if there are less than 15 lines. -d '\n' tells xargs to read full lines, instead of the possibly-quoted, whitespace separated words it does by default, and -r tells it to not run the command if there aren't any arguments. Neither is a standard feature.

ilkkachu
  • 138,973
  • i did change my condition to use -gt and my filenames are all consistent without whitespaces or newlines. thank you a lot for the command substitution advice! – fraxton Nov 06 '19 at 13:02