I call a command from the shell using shell-command-to-string
. However, I want not only its output, but also the command's exit code.
How do I get this?
You can execute an external shell command from within Emacs using ` M-! ' ( 'shell-command' ). The output from the shell command is displayed in the minibuffer or in a separate buffer, depending on the output size. When used with a prefix argument (e.g, ` C-u M-!
To quit Emacs permanently, type C-x C-c.
In a fresh Emacs window, type ESC-x lisp-interaction-mode . That will turn your buffer into a LISP terminal; pressing Ctrl+j will feed the s-expression that your cursor (called "point" in Emacs manuals' jargon) stands right behind to LISP, and will print the result.
shell-command-to-string
is just a convenience wrapper around more fundamental process functions.
A good function to use for simple synchronous processes is call-process
. Call process will return the exit code from the process and you can redirect all output to a buffer that you can use buffer-string
on to get the text.
Here's 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 "-r-w-r-- 1 ...")
Another note: if you end up wanting to do anything more complex with processes, you should read the documentation for start-process
, and how to use sentinals and filters, it is really a powerful api.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With