首页 > 解决方案 > Grep 和 pGrep 组成流程

问题描述

我根本不熟悉 bash,但我正在尝试制作一对能够检测到的脚本

  1. 如果一个程序正在运行。
  2. 如果 python/bash 脚本正在运行。

我的 nº1 代码是:

#!/bin/bash

X=$( pidof $1 )

if [ ${#X} -gt 0 ]
then
    echo "$1 has already $X been started"
else
    echo "$1 not started $X"
fi

效果很好,但不会检测到脚本,所以我做了第 2 次更改:

X=$( pgrep -f $1 )

起初 nº2 它似乎在工作,但是当我终止 python 脚本时,我仍然得到:

WebsocketServer has 5 length and it's already 11919 started

如果我这样做ps -ax,进程的 PID 将无处可见。

但如果我写ps -ax | grep websocket

11921 pts/4    S+     0:00 grep --color=auto websocket

如果我启动 python 脚本...

WebsocketServer has 11 length and it's already 11927 11935 started

怎么了?我是否以某种方式滥用命令?

编辑:忘了提到pgrep -f WebsocketServer在终端中写入什么都不会返回,就像它应该的那样。

标签: pythonbashraspberry-pi3

解决方案


问题是您的脚本的参数与您正在搜索的脚本名称相同,并且pgrep -f正在查找该脚本。

您可以尝试以下技巧:将名称拆分为两个参数。

checkScriptAlive websocket Server

然后在脚本中,执行:

target="$1$2"
x=$(pgrep -f "$target")

推荐阅读