如何在 Lua 的 if 语句中使用 Bash echo 作为条件?

我正在尝试编写一个用几个 Bash 命令检查进程是否正在运行的 Neovim Lua 函数;如果它正在运行,就关闭它,如果它没有运行,就运行一个新的实例。

这是我已经写好的代码:

isrunning = vim.cmd([[!pgrep -u $UID -x livereload > /dev/null && echo "true" || echo "false"]])
print(isrunning)

if isrunning == "true" then
  print('Closing Livereload...')
  vim.cmd('!killall livereload')
else
  print('Opening Livereload...')
  vim.cmd('!cd build; livereload &; firefox http://localhost:35729/"%<.html"')
end

问题在于即使 livereload 已经在运行,并且 isrunning 的值为 "true",if 语句的前半部分也不会运行,只有 else 后面的部分会运行。我需要改变什么才能解决这个问题?


更新:当在 Neovim 0.5.0 中运行上述代码时, :luafile % 的输出如下:

:!pgrep -u $UID -x livereload > /dev/null && echo "true" || echo "false"
true

:!cd build; livereload &; firefox http://localhost:35729/"livereload.html"

opening...

这让我想到第二行 true 必须是 print(isrunning) 命令的输出。在评论区进行了一些讨论之后,我意识到这并不是正确的。

当我将 print 命令更改为 print("Answer: " .. isrunning .. "Length: " .. isrunning:len()) 时,下面是输出:

:!pgrep -u $UID -x livereload > /dev/null && echo "true" || echo "false"
true

Answer: Length: 0
:!cd build; livereload &; firefox http://localhost:35729/"livereload.html"

opening...

因此,Neovim 正确显示了 !pgrep -u $UID -x livereload > /dev/null && echo "true" || echo "false" 的输出,但是这个输出似乎没有存储在变量 isrunning 中。

点赞
用户2858170
用户2858170

如果isrunning"true",那么您将进入if分支,但显然并非如此。

echo会添加一个尾随的换行符,因此isrunning更可能是"true\n",显然与"true"不相等。

使用echo -n来禁止尾随的换行符,或检查正确的值,或者使用string.findstring.match来替代==

来自bash手册

echo echo [-neE] [arg …] 输出参数,中间以空格分隔,以换行符结尾。返回值为0,除非发生写入错误。 如果指定了-n,则省略尾随的换行符...

2021-05-08 14:32:02
用户3969218
用户3969218

我最终想出了一个解决方案,分为两个部分:

  1. 使用 io.popen 和文件句柄的组合,就像 这个答案 中提到的那样,可以从 Lua 中读取 echo 的值。
  2. 使用 echo -n 来抑制换行符,就像 Piglet 在这个答案中所提到的那样。

有了这些改变,下面是最终代码:

handle = io.popen([[pgrep -u $UID -x livereload > /dev/null && echo -n "true" || echo -n "false"]])
isrunning = handle:read("*a")
handle:close()

if isrunning == "true" then
  print('closing...')
  vim.cmd('!killall livereload')
else
  print('opening...')
  vim.cmd('!cd build; livereload &; firefox http://localhost:35729/"%<.html"')
end
2021-05-12 19:13:24