Bash - 为什么这个条件没有做我认为它应该做的事情?

  • 本文关键字:条件 Bash bash shell scripting
  • 更新时间 :
  • 英文 :


这基本上是我在bash中的第一个脚本,所以我可能错过了一些非常简单的东西。

我不明白为什么即使firefox没有运行,"$(pgrep firefox)"似乎也会返回一些东西。

该脚本应该始终保持firefox实例运行。

#!/bin/bash
while true;
do
        if [ -z "$(pgrep firefox)" ]
                then
                        echo "firefox not running. Starting now..."
                        firefox
        fi
done
真正奇怪的是,如果我在bash命令提示符下输入这个,它会像预期的那样工作
if [ -z "$(pgrep firefox)" ];  then echo "not running"; fi

您是否尝试打印出$(pgrep firefox)的结果以查看返回的内容?

顺便说一下,这里不需要比较字符串。如果找到进程,pgrep返回true,否则返回false,因此您可以这样做:
if ! pgrep firefox
then
    echo firefox not running
fi

最新更新