I am new to shell scripting, so I need some help here. I have a directory that fills up with backups. If I have more than 10 backup files, I would like to remove the oldest files, so that the 10 newest backup files are the only ones that are left.
So far, I know how to count the files, which seems easy enough, but how do I then remove the oldest files, if the count is over 10?
if [ls /backups | wc -l > 10]
echo "More than 10"
ls -t | sed -e '1,10d' | xargs -d '\n' rm
This should handle all characters (except newlines) in a file name.
What's going on here?
ls -tlists all files in the current directory in decreasing order of modification time. Ie, the most recently modified files are first, one file name per line.
sed -e '1,10d'deletes the first 10 lines, ie, the 10 newest files. I use this instead of
tailbecause I can never remember whether I need
tail -n +10or
tail -n +11.
xargs -d '\n' rmcollects each input line (without the terminating newline) and passes each line as an argument to
As with anything of this sort, please experiment in a safe place.