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

查看:317
本文介绍了如何检查我的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"中找到自己的进程 怎么解决呢? 如何检查脚本是否已在运行或仅from that script?

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天全站免登陆