且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

shell脚本执行检查,如果它已经运行或不

更新时间:2023-11-26 08:27:16

要检查的过程已经在执行一个简单的方法是的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文件的presence检查,以确定是否处理已经在运行的一个简单的运动。

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,环路壳,甚至恢复到只是计算与的PID WC 以检测多个进程。

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