53

I want to run a shell command within Emacs and capture the full output to a variable. Is there a way to do this? For example, I would like to be able to set hello-string to "hello" in the following manner:

(setq hello-string (capture-stdout-of-shell-command "/bin/echo hello"))

Does the function capture-stdout-of-shell-command exist, and if so what is its real name?

3 Answers 3

85

Does shell-command-to-string meet your purpose?

For example:

(shell-command-to-string "/bin/echo hello")
Sign up to request clarification or add additional context in comments.

1 Comment

Note that shell-command-to-string captures both stdout and stderr. Luckily we can just pipe the stderr to /dev/null: (shell-command-to-string "/bin/echo hello 2>/dev/null")
30

I have a suggestion to made that extends Ise Wisteria's answer. Try using something like this:

(setq my_shell_output
  (substring 
    (shell-command-to-string "/bin/echo hello") 
   0 -1))

This should set the string "hello" as the value of my_shell_output, but cleanly. Using (substring) eliminates the trailing \n that tends to occur when emacs calls out to a shell command. It bothers me in emacs running on Windows, and probably occurs on other platforms as well.

7 Comments

I've noticed emacs doing that on both Mac OS X and on Linux, so it's not just NTEmacs.
(defun my-shell-command-to-string (&rest cmd) (replace-regexp-in-string "\r?\n$" "" (shell-command-to-string (mapconcat 'identity cmd " "))))
@spacebat You want \\' in there, not $.
echo hello is hello\n.
In linux/osx, you can use -n to stop outputting the trailing newline., e.g. echo -n hello
|
1

Finally, the "git log" "--reverse" option came in handy ). Open a buffer with the current buffer file as of the most initial commit.

(vc-revision-other-window (car (process-lines "git" "log" "--format=%h" "--reverse")))

And on the question of

(setq hello-string (car (process-lines "echo" "hello")))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.