How to Keep the Latest N (numbers) of Files or Backups Using Bash Script

This would help any Sysad who wants to retain or keep the latest backups or files automatically using a script.

Sample Codes Below:

#!/bin/bash
#
# This script retains 2 files
# Created by Burnz Barbosa
#
#
LOG_FILE="/var/log/retain_script.log"
cd /mnt/backups/full
num_files=`ls | wc -l`
rm `ls -tp | grep -v "/$" | awk '{ if (NR > 2) print; }'`
num_files2=`ls | wc -l`
/bin/echo "[$(date)]You have the latest $num_files2 retained in backup files " >> $LOG_FILE

Script Explanations:
The script is to keep the latest 2 files under /mnt/backups/full
1. We declare the log file at /var/log/ named as retain_script.log
2. Go to the backup directory, lets assumed /mnt/backups/full
3. Then we remove the count of oldest files and retain the latest 2
4. We ask to display the counts or number of files that it contains
5. We write a log with a date telling how many backups have retained and put it in the logfile

Spread the love

6 thoughts on “How to Keep the Latest N (numbers) of Files or Backups Using Bash Script

  1. Hi,

     

    Thanks for the script. I wanted to know what does the $ sign does  “grep -v “/$” ” ?

     

    I know  grep -v does invert match but just not able to understand $ part.

    Any help would be appreciated.

     

    Thanks,

    Jimy

     

    • Hi Jimy,

      That’s a good question!
      To explain further:
      grep – it print lines matching a pattern | -v – invert the sense of matching, to select non-matching lines (-v is specified by POSIX.) | “/$” – grep searches the named input FILEs (or standard input if no files are named, or if a single hyphen-minus (-) is given as file name) for lines containing a match to the given PATTERN. By default, grep prints the matching lines.

      I hope i was able to answer your question. 🙂

      Thank you!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.