我需要一个 .sh 文件,如果我的 python 服务未运行,它将回显 0。我知道这pgrep是我想要使用的命令,但我在使用它时遇到错误。
if [ [ ! $(pgrep -f service.py) ] ]; then
echo 0
fi
Run Code Online (Sandbox Code Playgroud)
这是我在网上找到的,但我一直收到错误
./test_if_running.sh: line 3: syntax error near unexpected token `fi'
./test_if_running.sh: line 3: `fi;'
Run Code Online (Sandbox Code Playgroud)
当我打字时
./test_if_running.sh
Run Code Online (Sandbox Code Playgroud)
您的代码中的问题是嵌套的[ ... ]. 另外,正如 @agc 所指出的,我们在这里需要检查的是退出代码pgrep而不是其输出。所以,正确的写法if是:
if ! pgrep -f service.py &> /dev/null 2>&1; then
# service.py is not running
fi
Run Code Online (Sandbox Code Playgroud)
这有点简单,但为什么不直接打印一个NOT退出代码,如下所示:
! pgrep -f service.py &> /dev/null ; echo $?
Run Code Online (Sandbox Code Playgroud)
作为奖励,1如果服务正在运行,它会打印出来。