Get back the output of os.execute in Lua

If you have io.popen, then this is what I use:

function os.capture(cmd, raw)
  local f = assert(io.popen(cmd, 'r'))
  local s = assert(f:read('*a'))
  f:close()
  if raw then return s end
  s = string.gsub(s, '^%s+', '')
  s = string.gsub(s, '%s+$', '')
  s = string.gsub(s, '[\n\r]+', ' ')
  return s
end

If you don’t have io.popen, then presumably popen(3) is not available on your system, and you’re in deep yoghurt. But all unix/mac/windows Lua ports will have io.popen.

(The gsub business strips off leading and trailing spaces and turns newlines into spaces, which is roughly what the shell does with its $(...) syntax.)

Leave a Comment