Lua os.execute return value

Cyclone picture Cyclone · Mar 13, 2012 · Viewed 92.7k times · Source

Is it possible to read the following from the local variable in Lua?

local t = os.execute("echo 'test'")
print(t)

I just want to achieve this: whatever is executed via the ox.execute and will return any value, I would like to use it in Lua - for example echo 'test' will output test in the bash command line - is that possible to get the returned value (test in this case) to the Lua local variable?

Answer

Lily Ballard picture Lily Ballard · Mar 13, 2012

You can use io.popen() instead. This returns a file handle you can use to read the output of the command. Something like the following may work:

local handle = io.popen(command)
local result = handle:read("*a")
handle:close()

Note that this will include the trailing newline (if any) that the command emits.