我以前一直使用一个脚本下载Ubuntu的源,Ubuntu 12.04的源,全部大概是120G,我1M带宽,要下载完,真的要10天时间。脚本运行过程中经常因为网络各种原因,中途退出和中断。
如果能让脚本退出后,自动继续运行呢?这是困惑我很久的问题,今天请教同事,终于搞定。
原理就是设置Crontab,检查一下脚本是否在运行,如果没有运行,就运行该脚本。如果在运行,就不进行任何操作。
我的ubuntu 下载脚本名字为:ubuntu_mirror.sh
编辑该脚本
在开始部分,增加下面内容
#!/bin/sh
appname=`basename $0`
nowdate=`date +%Y%m%d%H%M%S`
echo $$ > ${nowdate}.${appname}.pid
在脚本末尾,有两个退出 : exit 1 和 exit 0
就是在exit 1 和exit 0 上面添加一行
rm ${nowdate}.${appname}.pid
创建一个master.sh 脚本
appname=$1
if [ -e *.${appname}.pid ]; then
exit 0
else
echo "running"
nohup sh -x ./${appname} 1>${appname}.out 2>&1 &
fi
让脚本可运行
chmod +x master.sh
最后你需要设置crontab
运行命令
crontab -e
插入下面内容,表示10分钟运行一次.
0,10,20,30,40,50 * * * * /root/master.sh ubuntu_mirror.sh
这个时候,在脚本的目录里,可以看到一个类似 20131127223001.ubuntu_mirror.sh.pid 文件,就是脚本运行的进程id.
# cat 20131127223001.ubuntu_mirror.sh.pid
12549
脚本退出后,会删除这个文件.如果crontab检查到这个文件存在,就不会运行脚本,认为脚本正在运行.如果不存在pid脚本,就会运行该脚本.
无比感谢武同学的指导.