如何在lua中获取Shell脚本的返回值?

我在 Lua 中执行一个脚本:

os.execute("sh manager/scripts/update_system.sh" .. " " .. f)

我想获取脚本的输出(如果退出状态是 7,则返回 7)。

我尝试了

local output = os.execute("sh manager/scripts/update_system.sh" .. " " .. f)
print(output)

但它返回一些奇怪的数字,如 512

有什么办法解决这个问题吗?

点赞
用户3563994
用户3563994

似乎 os.execute 的输出都是 256 的倍数。别问我为什么,这一定是个 bug。

因此我这样做:

local exit = os.execute("sh manager/scripts/update_system.sh" .. " " .. f)
local value = exit / 256
print(value)

这样可以解决问题,但我想知道是否有其他解决方案。

2014-05-23 10:39:06
用户3629357
用户3629357

这适用于 Lua 5.1 和 Lua 5.2

exit_code = io.popen'your_command \necho _$?':read'*a':match'.*%D(%d+)'+0
2014-05-23 15:22:25