2015-07-04 at 5:43 PM UTC
in
Shell script thread
Here is a shitty script I wrote to help automate my backup process. It's meant to be used in conjunction with rsync. Say you have a folder
backup it will make a copy of it called backup_MM_YY for versioning. If it sees that there is no version for the current month one will be created. You specify how many versions and it will trim the old ones.
I did not realize bash functions couldn't handle named parameters and I can't bring myself to care enough to make the pieces more portable.
sortByTimeStampAndPurge () {
dir="/home/macfag/" # dir to work in
folder="gaypr0n" # file / folder base name to work with: baseName_mm_yy
curMonth=$(date +"%m")
curYear=$(date +"%y")
versions=3 # how many revisions to keep
lastMonth=""
lastYear=""
cd $dir
# firsts make array of folder names
i=0
files[0]=""
for f in ${folder}_*
do
files[i]=$f
((i++))
done
# sort them by actual timestamp
for (( i = (${#files[@]}-1); i >= 0; i-- )); do
for (( j = 1; j <= $i; j++ )); do
if [ $(stat -c %Y ${files[$j-1]}) -gt $(stat -c %Y ${files[$j]}) ]
then
tmp=${files[$j-1]}
files[$j-1]=${files[$j]}
files[$j]=$tmp
fi
done
done
# check there is an old copy
if [ ${files[${#files[@]}-1]} != "${folder}_*" ]
then
# if the last copy is labelled more than a month old: copy it
lastMonth=${files[${#files[@]}-1]:${#folder}+1:2}
lastYear=${files[${#files[@]}-1]:${#folder}+4:2}
if [ $curYear -gt $lastYear ]
then
cp -r $folder ${folder}_${curMonth}_${curYear}
files[${#files}]=${folder}_${curMonth}_${curYear}
elif [ $curMonth -gt $lastMonth ] && [ $curYear -eq $lastYear ]
then
cp -r $folder ${folder}_${curMonth}_${curYear}
files[${#files}]=${folder}_${curMonth}_${curYear}
fi
else
# there only exists the main backup, no versioning yet, create one
cp -r $folder ${folder}_${curMonth}_${curYear}
files[${#files}]=${folder}_${curMonth}_${curYear}
fi
# trim extra files that might exist
for (( i = ${#files[@]}-1; i >=0; i--)); do
if [ $versions -le 0 ]
then
rm -r ${files[$i]}
fi
((versions--))
done
}
sortByTimeStampAndPurge
The following users say it would be alright if the author of this
post didn't die in a fire!