Reputation: 6041
I have a list of files that looks like this:
...
live-2014-04-28.tar.bz2
live-2014-04-29.tar.bz2
live-2014-04-30.tar.bz2
live-2014-05-01.tar.bz2
live-2014-05-01.tar.bz2
live-2014-05-02.tar.bz2
...
... and trying to delete files older then a week with bash script:
c=0
for i in `echo "ls /filebackup/daily" | sftp somepath.your-backup.de`
do
c=`expr $c + 1`
[ $c -le 3 ] && continue
d=`echo $i | sed -r 's/[^0-9]*([0-9]+-[0-9]+-[0-9]+).*/\1/'`
d=`date -d $d +'%s'`
echo $c
if [ `expr $dc - 691200` -ge $d ]
then
echo 'here file will be deleted'
fi
done
I can't get inside echo 'here file will be deleted'
, was trying to debug – not quite sure what $dc
part does (I'm quite with coding in bash).
I'm using this code from this article (see The File-Backup-Script part), and trying to understand why it doesn't work on my side.
Thank you for any help.
Upvotes: 0
Views: 93
Reputation: 107040
rying to delete files older then a week with bash script.
What if you ignore the names of the files and just use the timestamp?
$ find . -name "live-*.tar.bz2" -mtime +7 -delete
It's not exactly what you want, but it's simple.
Upvotes: 1
Reputation: 77085
Here is one way of doing it.
#!/bin/bash
# Get the current and store in a variable
currDate=$(date +'%Y%m%d')
# set this shell option to prevent literal match when no files exists
shopt -s nullglob
# Iterate over your directory
for file in *.bz2; do
f=${file%%.*} # Strip the trailing extensions => live-2014-04-28
f=${f#*-} # Strip the leading hyphen => 2014-04-28
f=${f//-/} # Substitute all hyphens in date => 20140428
if (( f <= (currDate - 7) )); then # If the date is less than week old
echo rm $file ... # delete it
fi
done
I have put echo
before rm
command so that you can test the output. If you are satisfied with the result then you can remove the echo
.
Upvotes: 2