简体   繁体   中英

Delete files with filename pattern using bash script

I have this bash script that creates a backup of a database every 5 minutes that i run with crontab. At the end of the day, i want to delete the ones created and leave the last one created on that day.

Here's the contents of the script:

#! /bin/bash

DATE=$(date +"%Y%m%d%H%M")
mysqldump -ubackup_user db_to_backup > ~/backup/db_$DATE.sql
tar -zcvf ~/backup/db_$DATE.tar.gz ~/backup/db_$DATE.sql
rm ~/backup/db_$DATE.sql

Sample files created:

db_201312272300.tar.gz
db_201312272305.tar.gz
db_201312272310.tar.gz
db_201312272315.tar.gz
db_201312272320.tar.gz
db_201312272325.tar.gz
db_201312272330.tar.gz
db_201312272335.tar.gz
db_201312272340.tar.gz
db_201312272345.tar.gz
db_201312272350.tar.gz
db_201312272355.tar.gz
db_201312280000.tar.gz
db_201312280005.tar.gz
db_201312280010.tar.gz
db_201312280015.tar.gz

it should leave the following at the end of the day:

db_201312280000.tar.gz
db_201312280005.tar.gz
db_201312280010.tar.gz
db_201312280015.tar.gz

And have the following file copied/moved to a different directory:

db_201312272355.tar.gz

After midnight, run the following:

old=$(date +"%Y%m%d" -d yesterday)
mv "db_${old}2355.tar.gz" different/directory && rm "db_${old}*.tar.gz"

I connected the move and delete commands with && as a safety precaution. This way yesterday's backups are deleted only if the move of the 2355 backup is successful. If you are short on disk space and less concerned about backup integrity, replace the && with a ; (or a newline).

Separately, if, as per the script in the question, only one file is going into the tar file, then tar is superfluous. You could instead replace those two lines with:

mysqldump -ubackup_user db_to_backup | gzip >~/backup/db_$DATE.gz

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM