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

How to use Bash echo as a condition in a Lua if statement?

我正在尝试为 Neovim 编写一个 Lua 函数,在一些 Bash 命令的帮助下,检查进程是否 运行ning;如果它是 运行ning,则关闭它,如果不是,运行 一个新实例。

这是我到目前为止写的内容:

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已经是运行ning并且isrunning的值是"true",if语句的前半部分永远不会运行s,只有else之后的内容。我需要更改什么才能解决这个问题?


更新:这是:luafile %的输出,当上面的代码在Neovim 0.5.0中是运行时:

:!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("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.

如果isrunning"true"你会进入if分支,但显然不是这样。

echo 添加尾随换行符,因此 isrunning 更可能是 "true\n",这当然不等于 "true".

使用 echo -n 抑制尾随换行或检查与正确值的对比,或使用 string.findstring.match 而不是 ==

来自bash manual:

echo echo [-neE] [arg …] Output the args, separated by spaces, terminated with a newline. The return status is 0 unless a write error occurs. If -n is specified, the trailing newline is suppressed...

我终于想出了一个解决方案,它有两个方面:

  1. 使用io.popen和文件句柄的组合,如this answer中所写到另一个问题。这允许从 Lua.
  2. 中读取 echo 的值
  3. 使用 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