Wanting stdout, stderr and return code of shell commands

Q&A's, tips, howto's
Post Reply
Ishpeck
Posts: 14
Joined: Thu Jun 09, 2011 3:53 am

Wanting stdout, stderr and return code of shell commands

Post by Ishpeck »

When I use exec or ! to run a shell command, I want to get strings containing the contents of stdout and stderr (even if empty) as well as the exit code of the program.

I could direct the output in the command like so:
(! "ls 2>/tmp/err >/tmp/out")

And then just read those files but that seems horribly crufty.

Now exec gives me stdout but I still want exit code and stderr.

Is there a better way to see what is happening with the programs I run?

jef
Posts: 11
Joined: Sun May 18, 2014 8:42 am

Re: Wanting stdout, stderr and return code of shell commands

Post by jef »

Old post but it's worth a reply as I was also looking for a solution.
process and waitpid can be used. An example returning stdout/stderr
combined and the return code of the command:

Code: Select all

(define (exec2 cmd)
  (let ((pid) (out_r) (out_w) (output) (data))
    (map set '(out_r out_w) (pipe))
    (setq pid (process cmd 0 out_w))
    (close out_w)
    (while (read out_r data 1024)
           (extend output data))
    (list output (>> ((wait-pid pid) 1) 8))))
Examples of the execution of a successful and a failed command:

Code: Select all

> (exec2 "/bin/echo pouet")
("pouet\n" 0)

> (exec2 "/bin/ls /root")
("/bin/ls: cannot open directory /root: Permission denied\n" 2)

ralph.ronnquist
Posts: 216
Joined: Mon Jun 02, 2014 1:40 am
Location: Melbourne, Australia

Re: Wanting stdout, stderr and return code of shell commands

Post by ralph.ronnquist »

It depends on the platform of course. With bash and similar, you could also have

Code: Select all

(define (exec2 cmd) (exec (string cmd " 2>&1 ; echo $?"))
That will nicely parse and deliver the output (stdout and stderr) as a list of lines, with the addition of the return code as an additional string element at the end.

Post Reply