我是编写bash脚本的新手,所以我不明白如何修复(删除)if语句内的内容(参见下面的代码)。有人能告诉我它为什么会这样吗?
if pgrep "Electron" -n
then
killall Electron
else
echo "Visual Studio Code is already closed"
fi
Fromman pgrep
on MacOS:
-q Do not write anything to standard output.
所以你可以把条件改成:
if pgrep -q "Electron" -n
...
一个更通用的解决方案,应该与不支持-q
选项的pgrep
实现一起工作(例如在Ubuntu上),以及与任何其他工具,将进程的标准输出重定向到/dev/null
:
if pgrep "Electron" -n >/dev/null
...
可以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执行了该命令,您将在终端中看到它的输出。为了抑制输出,您可以使用重定向