`

bash编程之 crontab 定时任务

 
阅读更多

crontab  定时任务

# Example of job definition:

# .---------------- minute (0 - 59)

# |  .------------- hour (0 - 23)

# |  |  .---------- day of month (1 - 31)

# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...

# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat

# |  |  |  |  |

# *  *  *  *  * user-name command to be executed

 

*/5 * * * *   bash脚本名   每5分钟执行

0   2  * * *  bash脚本名   每天凌晨2点执行

0   2  7 * *  bash脚本名   每月7号凌晨2点执行

注: day of month + month 与 day of week  不同时使用

 

crontab命令:

-l: 显示当前用户的任务列表

-l -u username  显示其它用户的任务列表

-e:编辑任务

-r: 移除所有任务

 

练习.:每周2,4,7备份/var/log/messages文件至/backup/messages/目录中,文件名保存为形如messages-2017-03-27.tar.xz

0  0  *  *  2,4,7  /bin/cp -a /var/log/messages   backup/messages/messages-`/bin/date "+%Y-%m-%d"`

 

案例:重定向rm命令,使被删除的文件移动到recycle_bin目录。再写一个定时任务每天删除recycle_bin目录中7天前的文件

1. 添加文件/usr/local/recycle_bin/recycle_bin.sh

#!/bin/bash
count=0
dir=/tmp
if [ -d /tmp/recycle_bin ];then
	dir=/tmp/recycle_bin/`date +%F-%H-%M-%S`
	mkdir -p $dir
	for i in $*;do
		count=`echo $i|grep "^-"|wc -l`
		if [ $count -ne 1 ];then
			mv $i $dir
		else
			count=0
		fi
	done	 
else
	mkdir -p /tmp/recycle_bin 
        dir=/tmp/recycle_bin/`date +%F-%H-%M-%S`
        mkdir -p $dir
        for i in $*;do
                count=`echo $i|grep "^-"|wc -l`
                if [ $count -ne 1 ];then
                        mv $i $dir
                else
                        count=0
                fi
        done
fi

 

2. 重定向rm命令

 修改~/.bashrc, 如有要对所有用户生效就修改/etc/.bashrc 

 alias rm='rm -i' 改为:

 alias rm='/usr/local/recycle_bin/recycle_bin.sh'

 resource ~/.bashrc 

 

3. 添加文件/usr/local/recycle_bin/clear_recycle_bin.sh

#!/bin/bash
clear_dir=/tmp/recycle_bin/`date -d "7 day ago" +"%Y-%m-%d"`*
#clear_dir=/tmp/recycle_bin/`date %Y-%m-%d`*
/bin/rm -rf $clear_dir

 

4.添加定时任务

crontab -e 

30 11 */1 * * /usr/local/recycle_bin/clear_recycle_bin.sh

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics