40

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?

Tyler
  • 9,474
  • 1
  • 31
  • 54
Ryan C. Thompson
  • 37,328
  • 27
  • 87
  • 147

2 Answers2

65

Does shell-command-to-string meet your purpose?
For example:

(shell-command-to-string "/bin/echo hello")

Hope this helps.

Ise Wisteria
  • 10,349
  • 2
  • 37
  • 26
  • 2
    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")` – Yorick Sijsling May 08 '20 at 06:31
19

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.

Brighid McDonnell
  • 4,109
  • 3
  • 34
  • 59
Chris McMahan
  • 2,295
  • 1
  • 13
  • 9