線上環境有一些定時腳本(用crontab -l
可查看當前用戶的),有時咱們可能會改這些定時任務的腳本內容。爲避免改錯無後悔藥,需用shell實現一個程序,定時備份crontab中的.sh腳本文件shell
全部用戶的crontab放在/var/spool/cron/
目錄,各個用戶放在各自目錄下。只要把這些用戶的crontab讀取出來,提取出其中的.sh文件,而後按照用戶備份到相應目錄就行。最後配一個crontab,定時去執行這個備份程序。bash
#!/bin/bash # this shell script from https://www.cnblogs.com/itwild/ # backup dir # root user will in ${bak_dir}/root, itwild user will in ${bak_dir}/itwild bak_dir=/var/itwild # new file will end with 2020-02-24_00:28:56 bak_suffix=$(date '+%Y-%m-%d_%H:%M:%S') if [[ ! $bak_dir == */ ]]; then bak_dir="${bak_dir}/" fi create_dir_if_not_exist() { u="$1" user_bak_dir="${bak_dir}$u" if [ ! -d "$user_bak_dir" ]; then mkdir -p $user_bak_dir chown -R ${u}:${u} $user_bak_dir fi } backup_files() { u="$1" files=$2 for f in ${files[*]}; do if [[ $f == *.sh ]]; then # only backup file which end with .sh copy_file $u $f fi done } copy_file() { u="$1" filepath=$2 if [ ! -f "$filepath" ];then return fi user_bak_dir="${bak_dir}$u" filename=${filepath##*/} cur_ms=$[$(date +%s%N)/1000000] # avoid same filename here add cur_ms to distinct newfilepath="${user_bak_dir}/${filename}.${bak_suffix}.${cur_ms}" # switch to user and then copy file to right position su - $u -c "cp $filepath $newfilepath" } # start from here cd /var/spool/cron/ for u in `ls` do create_dir_if_not_exist $u files=$(cat $u | awk '{for(i=6;i<=NF;++i) printf $i" "}') backup_files $u "${files[*]}" done