bash if 语句将内容打印到终端

bash if statement prints stuff to terminal

我是编写 bash 脚本的新手,所以我不明白如何修复(删除)if 语句中的内容(参见下面的代码)。谁能告诉我为什么它会那样做?

    if pgrep "Electron" -n
        then 
            killall Electron
        else        
            echo "Visual Studio Code is already closed"
    fi

您可以 bash 重定向 https://www.gnu.org/software/bash/manual/html_node/Redirections.html


if pgrep "Electron" -n > /dev/null
        then 
            killall Electron 
        else        
            echo "Visual Studio Code is already closed" 
    fi

当您在 if 语句中传递 linux 命令时,bash 将 运行 此命令以检查其 退出代码 .此命令的退出代码将用于确定真或假。 在 bash 中,0 表示 true,任何其他退出代码的计算结果为 false。

因此,由于 bash 执行命令,您将在终端中看到它的输出。为了抑制输出,可以使用重定向

来自 man pgrep MacOS:

-q Do not write anything to standard output.

因此您可以将条件更改为:

if pgrep -q "Electron" -n
    ...

一个更通用的解决方案应该与不支持 -q 选项(例如 Ubuntu 的 pgrep 的实现以及任何其他工具一起使用将进程的标准输出重定向到 /dev/null:

if pgrep "Electron" -n >/dev/null
    ...