检查进程是否存在

End*_*der 2 bash process

我想编写接受进程名称的脚本(我每次都询问用户进程名称,然后在同一行上提示)如果进程存在,它将打印“存在”,如果不存在,则打印“不存在”,具体取决于系统上当前是否存在这样的进程。

例子:

Enter the name of process: bash
exists
Enter the name of process: bluesky
does not exist
Run Code Online (Sandbox Code Playgroud)

我的代码:

#!/bin/bash
while true
do
read -p "Enter the name of process: "
 if [ pidof -x > 0 ]; then
    echo "exists"   
 else    
    echo "does not exist"
 fi 
done 
Run Code Online (Sandbox Code Playgroud)

我收到的错误消息。

pidof: unary operator expected
Run Code Online (Sandbox Code Playgroud)

ste*_*ver 9

这里有一些事情需要纠正。

首先,尽管您通过 请求用户输入read,但您实际上并没有在任何地方使用结果。默认情况下,将读取的内容分配给名为您想要的read变量REPLYpidof -x "$REPLY"

其次,在[ ... ]POSIX 测试括号内,具有重定向运算符1>的普通含义。如果您检查当前目录,您可能会看到它现在包含一个名为. 整数“大于”测试是。0-gt

第三,你的pidof -x测试里面[ ... ]只是一个字符串;要将其作为命令执行并捕获结果,您需要命令替换

[ "$(pidof -x "$REPLY")" -gt 0 ]
Run Code Online (Sandbox Code Playgroud)

但是,pidof如果找到多个匹配进程,可能会返回多个整数 - 这将导致另一个错误。所以我建议直接使用退出状态pidof

EXIT STATUS
       0      At least one program was found with the requested name.

       1      No program was found with the requested name.
Run Code Online (Sandbox Code Playgroud)

所以你可以做

#!/bin/bash
while true
do
read -p "Enter the name of process: "
 if pidof -qx "$REPLY"; then
    echo "exists"
 else
    echo "does not exist"
 fi
done
Run Code Online (Sandbox Code Playgroud)

1在 bash[[ ... ]] 扩展测试中,>是一个比较运算符 - 但它执行字典比较而不是数字比较,所以你仍然想要-gt那里。不过,您可以在算术构造中使用>整数比较(( ... ))


ter*_*don 5

那是错误的测试。我的意思是你在问(好吧,你想问,但有语法问题)“PID是否大于0”,你应该问“是否至少有一个PID”。您可以用来pidof -q检查是否存在:

$ pidof -q bash && echo "exists" || echo "does not exist"
exists
$ pidof -q randomthing && echo "exists" || echo "does not exist"
does not exist
Run Code Online (Sandbox Code Playgroud)

你的脚本有很多问题。首先,当您read不使用变量时,该值存储在特殊变量中$REPLY,但您没有使用它。相反,您运行时pidox -x不带任何参数,并且始终不会返回任何内容。你想要这样的东西:

read -p "Enter the name of process: "
if pidof -x "$REPLY"; then ...
Run Code Online (Sandbox Code Playgroud)

但无论如何,请避免在启动脚本后询问用户输入。这仅仅意味着您的脚本无法自动化,用户可能会输入错误的值,并且整个事情更难毫无好处地使用。相反,将进程名称作为参数读取。

把所有这些放在一起,你想要这样的东西:

#!/bin/bash


if pidof -qx "$1"; then
    echo "There is at least one running process named '$1'"
 else    
    echo "There are no running processes named '$1'."
 fi 
Run Code Online (Sandbox Code Playgroud)

并像这样运行它:

script.sh processName
Run Code Online (Sandbox Code Playgroud)

例如:

script.sh bash
Run Code Online (Sandbox Code Playgroud)