如何以编程方式检查 ufw 是否正在运行

pka*_*mol 8 command-line ufw

在大多数服务(例如 privoxy)中,有一种干净的方法来获取服务状态: ps -C [servicename] 然后通过检查退出代码($?):0:服务正在运行 1:未运行 在 ufw 中不是这种情况(未被识别为服务?)sudo service ufw status无论 ufw 是否正在运行,总是以 0 退出。通过用于检查 ufw 状态的命令的退出代码以编程方式获取 ufw 的任何建议?

Syl*_*eau 12

由于返回的退出代码sudo ufw status始终为 0,因此您只需要grep获取状态值:

$ sudo ufw status
Status: inactive
$ sudo ufw status | grep -qw active
$ echo $?
1
Run Code Online (Sandbox Code Playgroud)

要正常工作,您必须使用该-w选项,从man grep

   -w, --word-regexp
          Select  only  those  lines  containing  matches  that form whole
          words.  The test is that the matching substring must  either  be
          at  the  beginning  of  the  line,  or  preceded  by  a non-word
          constituent character.  Similarly, it must be either at the  end
          of  the  line  or  followed by a non-word constituent character.
          Word-constituent  characters  are  letters,  digits,   and   the
          underscore.
Run Code Online (Sandbox Code Playgroud)

-q 只是安静模式,没有任何内容写入标准输出