capexec

function capexec( cmd ) --> exit, signal, stdout, stderr

Description

Executes a shell command cmd and returns also the captured output( stdout, stderr ).

Parameters

cmd

A shell command.

Return Values

exit

The exit status of the command, if it terminated normally.

signal

The signal that terminated the command, if it was terminated by a signal.

stdout

The standourt output that the execution of cmd generated.

stderr

The error output that the execution of cmd generated.

Code

--ZFUNC-capexec-v1
local function capexec( cmd ) --> exit, signal, stdout, stderr
   --ZFUNC-readfile-v1
   local function readfile( filename )
      local f, err = io.open( filename, "r" )
      if err then return nil, err end

      local str, err = f:read( "*a" )
      if err then return nil, err end

      local res, err = f:close()
      if err then return nil, err end

      return str
   end

   local outfile = os.tmpname()
   local errfile = os.tmpname()
   cmd = cmd..[[ >"]]..outfile..[[" 2>"]]..errfile..[["]]
   local exit, signal = os.execute( cmd )
   local outcnt = readfile( outfile )
   local errcnt = readfile( errfile )
   os.remove( outfile )
   os.remove( errfile )

   return exit, signal, outcnt, errcnt
end

return capexec

Inspired by

See also