加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

bash – shell脚本执行检查是否已经在运行

发布时间:2020-12-16 01:22:28 所属栏目:安全 来源:网络整理
导读:GNU bash,版本1.14.7(1) 我有一个脚本叫做“abc.sh” 我必须从abc.sh脚本检查这个… 里面我写了下面的声明 status=`ps -efww | grep -w "abc.sh" | grep -v grep | grep -v $$| awk '{ print $2 }'`if [ ! -z "$status" ]; then echo "[`date`] : abc.sh : P
GNU bash,版本1.14.7(1)

我有一个脚本叫做“abc.sh”
我必须从abc.sh脚本检查这个…
里面我写了下面的声明

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’
怎么解决?
如何检查该脚本是否已经从该脚本运行?

检查已经执行的进程的更简单的方法是pidof命令.
if pidof -x "abc.sh" >/dev/null; then
    echo "Process already running"
fi

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

#!/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以检测多个进程.

以下是一个例子:

#!/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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读