Bash Script for deleting old backup files -
every night server creates backups every mysql database. of these files saved in folder /backup/mysql/2014-11-28. on last few months lot of folders , files have been stored in directory , reduce this.
therefore need bash script deletes every folder in given directory, except every folder created month (not in last 30 days, actual month) , except 1 backup every week (for example backup sunday). since have no clue how sunday party decided simpler keep backups 07th, 14th, 21st , the 28th.
#!/bin/bash in_array() { local haystack=${1}[@] local needle=${2} in ${!haystack}; if [[ ${i} == ${needle} ]]; return 0 fi done return 1 } year=`date +%y` lastyear=`date +%y -d "1 year ago"` month=`date +%m` days="07 14 21 28" in $( ls ); backup_year=$(echo "${i}" | cut -d'-' -f1) backup_month=$(echo "${i}" | cut -d'-' -f2) backup_day=$(echo "${i}" | cut -d'-' -f3) delete=false if [[ "$backup_year" == "$year" ]]; if [[ "$backup_month" != "$month" ]]; if [ $(in_array $days "$backup_day") ]; delete=true fi fi fi if [[ "$backup_year" == "$lastyear" ]]; if [[ "$backup_day" != ${days[0]} ]]; delete=true fi fi if [ "$delete" = true ] ; #output=`rm -v -r $i` echo $i fi done
the second part (backups year before) works fine, first part (for backups year) doesn't work , don't know why. found function on site, guess somehow call wrong.
edit: code using:
#!/bin/bash read year month <<<$(date "+%y %m") lastyear=$(( year-1 )) days=" 07 14 21 28 " fn in $( ls ) if ([ "${fn:0:4}" = "$year" ] && [ "${fn:5:2}" != "$month" ] && [ "${days/ ${fn:8:2} /}" = "$days" ]) || ([ "${fn:0:4}" = "$lastyear" ] && [ "${fn:8:2}" != ${days:1:2} ]) #output=`rm -v -r $fn` echo "$fn" fi done
#!/bin/bash read year month <<<$(date "+%y %m") lastyear=$(( year-1 )) days=" 07 14 21 28 " fn in $( ls ) delete=false if [ "${fn:0:7}" = "$year-$month" ] && [ "${days/ ${fn:8:2} /}" != "$days" ] delete=true elif [ "${fn:0:4}" = "$lastyear" ] && [ "${fn:8:2}" != ${days:1:2} ] delete=true fi if [ "$delete" = true ] #output=`rm -v -r $fn` echo "$fn" fi done
assuming file name matches following date format yyyy-mm-dd
, instance, 2014-03-27
, expression ${fn:0:7}
2014-03
; ${fn:8:2}
27
; ${fn:0:4}
2014
.
read bash manual pages parameter expansion.
the expression ${days/ ${fn:8:2} /}
checks day filename (wrapped white spaces) found in days
list. equivalent echo "${days}" | grep -q "${backup_day}"
.
note: possible reduce commands inside for
loop (join if
, elif
means of ||
, remove delete
variable checking , delete
variable itself) decided keep of original script.
Comments
Post a Comment