Grep和pGrep组成过程

时间:2018-08-09 11:55:50

标签: python bash raspberry-pi3

我对bash一点都不熟悉,但是我正在尝试制作一对可以检测到的脚本

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

我的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

哪个功能很好,但不会检测脚本,所以我将更改设为nº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并不会产生任何回报。

1 个答案:

答案 0 :(得分:1)

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

这是您可以尝试的技巧:将名称分成两个参数。

checkScriptAlive websocket Server

然后在脚本中执行:

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