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

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

posted @ 2016-09-07 14:02  zolo®  阅读(527)  评论(0编辑  收藏  举报