如何从脚本本身检查脚本是否正在运行? [英] How to check if script is running or not from script itself?

查看:318
本文介绍了如何从脚本本身检查脚本是否正在运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面有示例脚本sample.sh

#!/bin/bash

if ps aux | grep -o "sample.sh" >/dev/null
then
    echo "Already script running"
    exit 0
fi

echo "start script"

while true
do
    echo "script running"
    sleep 5
done

在上面的脚本中,我要检查此脚本先前是否正在运行,如果正在运行,则不要再次运行它.

In above script i want to check if this script previously running or not if running then not run it again.

问题是检查条件始终为真(因为检查条件需要运行脚本),并且总是向我显示"Already script running"消息.

problem is check condition always become true (because to check the condition require to run script) and it always show me "Already script running" message.

有什么办法解决吗?

推荐答案

您需要适当的锁.我会像这样使用 flock :

You need a proper lock. I'd do using flock like this:

exec 201> /tmp/lock.$(basename $0).file
if ! flock -n 201  ; then
  echo "another instance of $0 is running";
  exit 1
fi

# cmds 

exec 201>&- 
rm -rf  /tmp/lock.$(basename $0).file

这基本上是使用临时文件为脚本创建锁.临时文件除了用来告诉您的脚本是否已获得锁定外,还具有特殊的意义. 当该程序的一个实例正在运行时,该程序的下一次运行将无法运行,因为锁会阻止它运行.

This basically creates lock for script using a temporary file. The temporary file has particular significance other than it's used to tell whether your script has acquired a lock. When there's an instance of this program running, the next run of the same program can't run as the lock will prevent it.

这篇关于如何从脚本本身检查脚本是否正在运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆