我有一个每 4 分钟运行一次的 Cron 作业脚本。在极少数情况下,脚本未在 4 分钟内完成。这会导致问题。
如何执行检查,如果前一个脚本未完成,则跳过当前运行
预期行为:
10:00 : Script A starts
10:04 : Script A2 starts - it finds that script A was not finish so this script aborts. Simply finish without doing nothing.
10:06 : Script A finish
10:08 : Script A3 starts - no other scripts running so it continue
Run Code Online (Sandbox Code Playgroud)
注意:A、A2、A3是同一个剧本(只是时间不同)!它不应该考虑可能正在运行的其他脚本
主要有两种方法:
如果脚本检测到自身正在运行的另一个实例,则使脚本退出。只需将这些行添加到脚本的开头:
if [ $(pgrep -c "${0##*/}") -gt 1 ]; then
echo "Another instance of the script is running. Aborting."
exit
fi
Run Code Online (Sandbox Code Playgroud)
$0是脚本的名称,并且${0##*/}是脚本的名称,直到最后一次/删除为止(因此,/path/to/script.sh变为script.sh)。这意味着如果您有另一个同名的不相关脚本正在运行,它仍然会被检测到。另一方面,这也意味着即使您从符号链接调用脚本它也能工作。您更喜欢哪一种取决于您的用例。
如果文件存在,则使用锁定文件并退出脚本:
#!/bin/bash
if [ -e "/tmp/i.am.running" ]; then
echo "Another instance of the script is running. Aborting."
exit
fi
else
touch "/tmp/i.am.running"
fi
## The rest of the script goes here
rm "/tmp/i.am.running"
Run Code Online (Sandbox Code Playgroud)