Shell 脚本避免重复执行的方法

参考:
Shell脚本避免重复执行的方法
https://m.jb51.net/article/60285.htm
Shell特殊变量:Shell $0, $#, $*, $@, $?, $$和命令行参数
https://www.cnblogs.com/davygeek/p/5670212.html
linux shell 字符串操作(长度,查找,替换)详解
https://www.cnblogs.com/chengmo/archive/2010/10/02/1841355.html
shell脚本--逻辑判断与字符串比较
https://www.cnblogs.com/-beyond/p/8262265.html


只需要在单例模式的脚本最开始处加上以下这段代码即可避免重复执行

# Get the fullname of proces with full path
basePath=$(cd `dirname $0`; pwd)
fullPathProc=$basePath/${0##*/}

# Run the proces by fullname
if [ $fullPathProc != $0 ]; then
  /bin/bash $fullPathProc
  exit 1
fi

# Check if the proces is running
pCount=$(ps -ef | grep $fullPathProc | grep -v 'grep' | grep -v ' -c sh' | grep -v $$ | grep -c 'sh')
if [ $pCount -gt 0 ]; then
  echo "$fullPathProc is running ..." 
  exit 0
fi

echo "$fullPathProc is starting now ..."
sleep 1800


例如保存成t.sh,然后在两个终端中运行sh t.sh 以验证效果。

解释:
$0: 当前脚本名字,不一定包含完整路径
$$: 当前脚本的进程ID 即PID,也是其子shell 的PPID,过滤掉它可以排除本进程及子进程
grep -v ' -c sh': crontab 运行的脚本会多一个-c sh 的进程
grep -c 'sh': 统计关键字sh 的数量即count
 

发布了27 篇原创文章 · 获赞 4 · 访问量 9695

猜你喜欢

转载自blog.csdn.net/yoshubom/article/details/88544909
今日推荐