shell指令碼批量壓縮log檔案並備份
阿新 • • 發佈:2018-11-12
需求:
每天有排程任務執行,會產生大量log等檔案。導致伺服器空間報警不足。又不能直接rm掉。所以壓縮後弄到備份機器上。
log目錄多如:
根據檔名匹配出6個月前的檔案。進行壓縮備份。並rm掉以省出空間。
壓縮後:
指令碼描述:
work_path:自動獲取當前檔案所在絕對路徑;
set timeout:expect的超時時間。單位S,設定-1時為永不超時。
#clear six months ago files to tar and scp... echo "Please wait..." work_path=$(dirname $(readlink -f $0)) #get now_path fileEnd=${work_path##*/}; m=`date -d "6 months ago" +%Y%m` #now=`date -d "0 months ago" +%Y%m` index=0 f=`ls $work_path -1 -c` for name in $f do n=`expr "$name" : '.*\([0-9]\{8\}\).*'` if [ "$n" != "" ] && [ "$n" -le "$m"31 ] then f[$index]="$work_path/$name" else f[$index]="" fi (( index ++ )) done str=${f[@]} if [ "${#str}" -gt 0 ] then tar -zcvf $work_path/logbak_$m.tar.gz $str && rm -rf $str echo "tar.gz finished!" else echo"No files found." exit 0 fi echo "tar.gz maked, now delete old files." #rm -fr $str echo "rm finished,start scp to ptfLogsBackup" backupMachine=你的遠端備份ip; backupMachinePath=備份ip的目的path; set timeout 300 ##if bak_file not exists,creating... /usr/bin/expect<<EOF spawn ssh 遠端ip的[email protected]$backupMachine "\[ -d $backupMachinePath/$fileEnd \] && echo ok, file exists.. || mkdir -p $backupMachinePath/$fileEnd" expect "password:" send "遠端ip的password\r" expect EOF EOF #scp sending... /usr/bin/expect<<EOF spawn bash -c "scp -r $work_path/*.tar.gz 遠端ip的[email protected]$backupMachine:$backupMachinePath/$fileEnd && rm -rf $work_path/*.tar.gz" expect "password:" send "遠端ip的password\r" expect EOF EOF echo "scp tar.gz files finished!" echo "done." exit 0
參考:
瞭解shell中、、有的地方寫的有點爛。每天學習一點