0

I have a directory containing files named like

SLS20160112.001    (20160112 stands for YYYYMMDD)

I wish to archive all previous month's files. For example, given:

SLS20150201.001
SLS20160107.001
SLS20160130.001
SLS20160201.001

I will archive SLS20160107.001 and SLS20160130.001 because these two files have a January 2016 name and it's currently February 2016.

For the SLS20160201.001 (February 2016) should not be archived, as I only want to archive previous month's file. Note that I can only consider the filename, not the mtime or atime

My current logic is to loop through all files, then get previous month files and then pipe out the filename and tar it. But not sure how to do that part.

for file in SLS*; do
   f="${file%.*}"

GET PREVIOUS MONTH FILES AND THEN ECHO

done | tar cvzf SlSBackup_<PREVIOUS_MONTH>.TAR.GZ -T-
3

With GNU date, you can use the -d switch and plain-English descriptions to get an arbitrary date. For example, date -d "one month ago". So, we can work thusly:

FILESPEC="SLS$(date -d "1 month ago" +"%Y%m")??.001"
LASTMONTH="$(date -d "1 month ago" +"%m")"
IFS=

tar cvzf "SlsBackup_${LASTMONTH}.tar.gz" $FILESPEC

Happily, this is smart enough that if you run it in, say, Jan 2017, it will rightly back up the files for Dec 2016.

  • is there any command for 1 year ago? maybe like LASTYEAR="$(date -d "1 year ago" +"%m")" – hades Feb 26 '16 at 6:13
  • There sure is. It's pretty interesting to see just how robust the -d parsing is. You can even do such craziness as date -d 'tuesday last week or date -d '464 days ago. See the DATE STRING section of date's manual page. – DopeGhoti Feb 26 '16 at 6:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.