bash - 如何确保我的 bash 脚本尚未运行?

标签 bash

我有一个 bash 脚本,我想从 cron 每 5 分钟运行一次...但是之前的脚本运行有可能还没有完成...在这种情况下,我希望新的运行退出.我不想只依赖/tmp 中的锁定文件。我想确保在我接受锁定文件(或其他)之前该进程确实在运行...

这是我到目前为止从互联网上偷来的东西……我该如何让它更聪明一点?还是有更好的完全不同的方式?

if [ -f /tmp/mylockFile ] ; then
  echo 'Script is still running'
else
  echo 1 > /tmp/mylockFile
  /* Do some stuff */
  rm -f /tmp/mylockFile
fi

最佳答案

# Use a lockfile containing the pid of the running process
# If script crashes and leaves lockfile around, it will have a different pid so
# will not prevent script running again.
# 
lf=/tmp/pidLockFile
# create empty lock file if none exists
cat /dev/null >> $lf
read lastPID < $lf
# if lastPID is not null and a process with that pid exists , exit
[ ! -z "$lastPID" -a -d /proc/$lastPID ] && exit
echo not running
# save my pid in the lock file
echo $$ > $lf
# sleep just to make testing easier
sleep 5

此脚本中至少存在一个竞争条件。不要将它用于生命支持系统,大声笑。但它对于您的示例应该可以正常工作,因为您的环境不会同时启动两个脚本。有很多方法可以使用更多原子锁,但它们通常取决于有选择地安装特定的东西,或者在 NFS 上以不同的方式工作等......

关于bash - 如何确保我的 bash 脚本尚未运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1440967/

相关文章:

macos - -bash : otool: command not found, 你能教bash一个默认位置来查找命令吗?

linux - 使用 Bash 删除具有特定模式的行

linux - 当我 sudo bash -c 时会发生什么?

linux - Bash 修改 CSV 以更改字段

bash - 在 bash 中干净地转储关联数组内容的简单方法?

Bash:如何转义 $@?

regex - Bash 脚本正则表达式

regex - 如何修复目录名: missing operand

bash - 如何在 bash shell 脚本中设置别名以便从外部可见?

c - C 中的简单 Shell