红联Linux门户
Linux帮助

bash:避免命令重复执行的简单脚本

发布时间:2016-09-07 15:51:02来源:linux网站作者:zolo®
1.根据命令生成md5做为文件名保存当前进程的pid
2.使用exec执行命令
3.如果再次执行, 使用ps -p检测上次pid是否有效, 如果是则exit 200.否则重复1.
hadoop@ubuntu102:~$ cat guard
#!/bin/bash
declare fpid=/tmp/$(echo -n "$@"|md5sum|awk '{print $1}');
if [[ -f ${fpid} ]];then
read pid < ${fpid} && ps -p ${pid:-0} > /dev/null && if [[ $? -eq 0 ]];then echo "previous process still running...${pid}, $*" && exit 200; fi
fi
echo $$ > ${fpid}
exec $*
hadoop@ubuntu102:~$ ./guard sleep 10 &
[1] 4070
hadoop@ubuntu102:~$ ./guard sleep 10
previous process still running...4070, sleep 10
hadoop@ubuntu102:~$ ./guard sleep 10
previous process still running...4070, sleep 1
 
本文永久更新地址:http://www.linuxdiyf.com/linux/23967.html