crontab 日志备份定时任务

时间:2022-06-12 19:28:10

-l选项,查看当前用户的所有定时任务:

[xiluhua@vm-xiluhua][/home]$ crontab -l
* * * * * /home/xiluhua/shell_script/logbk.sh

 

-e选项,创建或修改当前用户的定时任务:

[xiluhua@vm-xiluhua][/home]$ crontab -e
crontab: no changes made to crontab

 

-u选项,查看(-l),修改(-e)指定用户的定时任务,(仅root管理员可用):

[root@vm-xiluhua][/home]$ crontab -u xiluhua -l
* * * * * /home/xiluhua/shell_script/logbk.sh

-r选项,删除定时任务

 

配置文件:

[xiluhua@vm-xiluhua][~/shell_script]$ cat logbk.conf 
logbk.sh 1 /home/xiluhua/auto log

代码:

[xiluhua@vm-xiluhua][~/shell_script]$ cat logbk.sh
#!/bin/bash
#author:xiluhua
#since:20160619
 
#####################################################################
# $1: name of log*.sh to execute log-backuping
# $2: size triggers log backuping
# $3: directories need to log-backup 
# $4: postfix with which log file will be backuped
#####################################################################
 
v_name=$0
v_name=${v_name##*/}
v_exce="exception@${v_name}"
v_nohup="/home/xiluhua/shell_script/nohup_logbk.out"
v_conf="/home/xiluhua/shell_script/logbk.conf"
v_date=".$(date +%Y%m%d'_'%H%M%S)"
 
declare -i v_isConfiged=1 #0true1false
[ ! -s $v_conf ] && echo "exception@conf.error:please check if $v_conf is available!" >> $v_nohup && exit 1
 
while read -r f1 f2 f3 f4
do
        if [[ -n $f1 && $f1 == $v_name ]]
        then
                [ -z "$f2" ] && echo "$v_exce@2:size triggers log backuping can not be null" >> $v_nohup && exit 1
        [ -z "$f3" ] && echo "$v_exce@3:directories need to log-backup can not be null" >> $v_nohup && exit 1
        [ -z "$f4" ] && echo "$v_exce@4:log postfix can not be null" >> $v_nohup && exit 1
        v_size=$f2
        v_dir=$f3
                v_postfix=$f4
                v_isConfiged=0
        break
        fi
done<"$v_conf"
 
[ $v_isConfiged == 1 ] && echo "$v_exce@1:not appropriate configed" >> $v_nohup && exit 1
 
v_line=""
for (( i=0;i<80;i++))
do
        v_line=$v_line"="
done
echo $v_line >> $v_nohup
echo "pid:"$$ >> $v_nohup
echo "v_size:"$v_size"M" >> $v_nohup
echo "v_dir:"$v_dir >> $v_nohup
echo "v_postfix:"$v_postfix >> $v_nohup
IFS=";"
echo "=== dirs listening ===" >> $v_nohup
for dir in $v_dir
do
        echo "this.dir:"$dir >> $v_nohup
        for postfix in $v_postfix
        do 
                echo "find $dir -size +${v_size}M -name '*.$postfix'" >> $v_nohup
 
                #find $dir -size +${v_size}M -name "*.$postfix" -exec gzip {} \;
                for file in $(find $dir -size +${v_size}M -name "*.$postfix")
                do
                        echo "log files to be backuped:" >> $v_nohup
                        echo $file >> $v_nohup
                        gzip -c $file > ${file}${v_date}.gz && echo > $file
                done
 
                #find $dir -size +${v_size}M -name "*.$postfix" -exec gzip {} \; 
        done
done
exit 0