I am new to bash script. I need to keep file for retention period of one month and archive other.


File format: WE20160225.log (20160225 YYYYMMDD)

Say in the directory /oracle/Sales has 2 files:



I need to tar the WE20151201.log

But not WE20160130.log because the file is less than one month from now. How can I do this? (probably need to substring the filename)

I'm able to change directory but don't know what to do next. My logic is loop through the file and get the date from filename, then compare with current date.

I need to use the filename date, not the file modification date.

  • 2
    Any reason not to use find to check on modification time (instead some number sequence that might, or might not be available as part of the filename and could be interpreted as a date? And then you create the tar file from the resulting file list.
    – Anthon
    Commented Feb 25, 2016 at 13:01
  • tar is not a tool that will expire files. backup software are.
    – Archemar
    Commented Feb 25, 2016 at 13:39
  • Can you expand on your question and confirm if the file modification dates line up with the filename date/times (if they do, find can be used, if not, some other technique is required). Commented Feb 25, 2016 at 13:59

3 Answers 3


I use something like this:

find <dir> -name <pattern> -mtime <timeframe> -exec <cmd> <options> {} \;
find . -type f -name '*log*' -mtime +10 -exec tar -rvf backup$(date +"%m-%d-%y") {} \;

finds files with log in their name that are older than 10 days. Creates a tar archive with todays date and appends all the files. You could also do away with the $date and append only new files, then semicolon and remove the file with rm {} \;


You can use something like this:

find somedir/* -mtime +5 -exec rm {} \;

It used find to find files older than 5 days and passes the found file over to delete.


Here is the script for compressing month old log files.

files=($(find /oracle/Sales -mtime +30))
tar cvfz backup.tar.gz "${files[@]}"

-mtime +number-of-days to describe the file which you need to backup.

For deleting the older file try this

find /oracle/Sales -mtime +30 | xargs -n1 echo rm

If you get the right output then remove echo from the line.

  • Assumes (maybe correctly, but maybe not) that the file has a timestamp which matches the filename, maybe sales data is written one month in arrears or maybe the file timestamps are different for some other reason. This might work but it's not a certainty. Commented Feb 25, 2016 at 13:58

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .