【问题标题】:Check if output of a shell command is empty in Lua检查 Lua 中 shell 命令的输出是否为空
【发布时间】:2017-06-14 07:50:03
【问题描述】:

只有当pgrep -x foo 的输出为空时,我才尝试激活一些 Lua 行。我尝试了以下方法:

if os.execute("pgrep -x foo") then
   -- My lines here
end

但是,这似乎不是正确的解决方案,即使在语法上也可以。

【问题讨论】:

    标签: bash shell lua command conditional


    【解决方案1】:

    也许尝试检查nil

    if os.execute('pgrep -x foo') == nil then
        print('empty')
    end
    

    如果您不希望匹配“精确”,则删除 -x 选项。

    【讨论】:

      【解决方案2】:
      local result = os.execute("pgrep -x foo")
      if result ~= true and result ~= 0 then
         -- My lines here (no such process)
      end
      

      【讨论】:

      • @JoeC 有些事情告诉我,Egor 已经存在了一段时间;)
      • 您能解释一下为什么要使用两个条件吗?我认为你的答案是正确的,但我不理解它的全部内容。
      • @xvlaze - os.execute 为 Lua 5.15.2+ 返回不同的结果。条件result ~= true and result ~= 0 无处不在。
      猜你喜欢
      • 1970-01-01
      • 2018-09-30
      • 2016-05-25
      • 2010-11-18
      • 1970-01-01
      • 2021-04-13
      • 2012-05-06
      • 2013-05-31
      相关资源
      最近更新 更多