Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the exit code of a shell command in elisp

Tags:

emacs

elisp

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?

like image 503
Clark Gaebel Avatar asked Apr 25 '14 17:04

Clark Gaebel


People also ask

How to execute shell commands in Emacs?

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-!

How do I exit Emacs shell?

To quit Emacs permanently, type C-x C-c.

How do I run a lisp in Emacs?

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.


1 Answers

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.

like image 152
Jordon Biondo Avatar answered Sep 27 '22 18:09

Jordon Biondo