如何检查我的 shell 脚本的另一个实例是否正在运行 [英] How to check if another instance of my shell script is running

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

问题描述

GNU bash,版本 1.14.7(1)

GNU bash, version 1.14.7(1)

我有一个脚本叫做abc.sh"我只需要从 abc.sh 脚本中检查这个...在里面我写了以下声明

I have a script is called "abc.sh" I have to check this from abc.sh script only... inside it I have written following statement

status=`ps -efww | grep -w "abc.sh" | grep -v grep | grep -v $$ | awk '{ print $2 }'`
if [ ! -z "$status" ]; then
        echo "[`date`] : abc.sh : Process is already running"
        exit 1;
fi

我知道这是错误的,因为每次它在'ps'中找到自己的进程时退出如何解决?我怎样才能检查脚本是否已经在运行?仅来自那个脚本?

I know it's wrong because every time it exits as it found its own process in 'ps' how to solve it? how can I check that script is already running or not from that script only ?

推荐答案

pidof 命令是检查已执行进程的更简单方法.

An easier way to check for a process already executing is the pidof command.

if pidof -x "abc.sh" >/dev/null; then
    echo "Process already running"
fi

或者,让您的脚本在执行时创建一个 PID 文件.然后是检查 PID 文件是否存在以确定进程是否已在运行的简单练习.

Alternatively, have your script create a PID file when it executes. It's then a simple exercise of checking for the presence of the PID file to determine if the process is already running.

#!/bin/bash
# abc.sh

mypidfile=/var/run/abc.sh.pid

# Could add check for existence of mypidfile here if interlock is
# needed in the shell script itself.

# Ensure PID file is removed on program exit.
trap "rm -f -- '$mypidfile'" EXIT

# Create a file with current PID to indicate that process is running.
echo $$ > "$mypidfile"

...

更新:问题现在已更改为从脚本本身检查.在这种情况下,我们希望总是看到至少一个 abc.sh 正在运行.如果有多个abc.sh,那么我们知道该进程仍在运行.我仍然建议使用 pidof 命令,如果进程已经在运行,它会返回 2 个 PID.您可以使用 grep 过滤掉当前的 PID,在 shell 中循环,甚至可以使用 wc 恢复到仅计算 PID 以检测多个进程.

Update: The question has now changed to check from the script itself. In this case, we would expect to always see at least one abc.sh running. If there is more than one abc.sh, then we know that process is still running. I'd still suggest use of the pidof command which would return 2 PIDs if the process was already running. You could use grep to filter out the current PID, loop in the shell or even revert to just counting PIDs with wc to detect multiple processes.

这是一个例子:

#!/bin/bash

for pid in $(pidof -x abc.sh); do
    if [ $pid != $$ ]; then
        echo "[$(date)] : abc.sh : Process is already running with PID $pid"
        exit 1
    fi
done

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

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