Finding shell command exit code in elisp

I am invoking a command from the shell using shell-command-to-string . However, I want not only its output, but also the command exit code.

How to get it?

+7
emacs elisp
source share
1 answer

shell-command-to-string is just a convenient wrapper around the more fundamental functions of a process.

A good feature for simple synchronous processes is call-process . The call process returns the exit code from the process, and you can redirect all the output to a buffer, which you can use buffer-string to get the text.

Here is an example:

 ;; this single expression returns a list of two elements, the process ;; exit code, and the process output (with-temp-buffer (list (call-process "ls" nil (current-buffer) nil "-h" "-l") (buffer-string))) ;; we could wrap it up nicely: (defun process-exit-code-and-output (program &rest args) "Run PROGRAM with ARGS and return the exit code and output in a list." (with-temp-buffer (list (apply 'call-process program nil (current-buffer) nil args) (buffer-string)))) (process-exit-code-and-output "ls" "-h" "-l" "-a") ;; => (0 "-rwr-- 1 ...") 

One more note: if you want to do something more complex with processes, you should read the documentation for the start-process , as well as use alerts and filters, this is a really powerful api.

+13
source share

All Articles