Reputation: 392
I have a folder that contains database backups, but i want to automate it using cron to delete old backups.
so i created the following script
#Get the current year
YEAR=$(date +'%Y')
#Get the current month
MONTH=$(date +'%m')
#Delete data from previous months
deleteOldData() { ls /root/copy/dbbackup/smpp_credits/ | awk -F "-" -v m="$MONTH" '$2 < m' | xargs -d "\n" rm -rf ;}
#Delete data from previous years ( if any )
deletePrevYearData() { ls /root/copy/dbbackup/smpp_credits/ | awk -F "-" -v y="$YEAR" '$3 < y' | xargs -d "\n" rm -rf ;}
deleteOldData
deletePrevYearData
Executing ls /root/copy/dbbackup/smpp_credits/ | awk -F "-" -v m="$MONTH" '$2 < m'
in the terminal works as expected, (it lists the required files).
but upon appending | xargs -d "\n" rm -rf
the code runs and returns without any output, and checking the directory reveals that the files are still there. By the way, this code is stored and executed from a .sh file
Upvotes: 0
Views: 46
Reputation: 222
Parsing ls
output is widely considered to be a bad idea. I would try a find command, which should be cleaner.
find /root/copy/dbbackup/smpp_credits/ -maxdepth 1 -mtime +365 -exec rm -rf {} \;
from here. You can use -mtime +30
for files that are older than one month.
Upvotes: 1
Reputation: 295687
Assuming GNU find
and date
, -newermt
can be used to compare a file's modification time against a specific date given as an argument:
delete_older_than_date="$(date +'%Y-%m-01')"
find /root/copy/dbbackup/smpp_credits \
-maxdepth 1 \
-type f \
'!' -newermt "$delete_older_than_date" \
-exec rm -rf -- '{}' +
Upvotes: 1