Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to capture standard output of a shell command in elisp?

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?

like image 810
Ryan C. Thompson Avatar asked Feb 16 '11 08:02

Ryan C. Thompson


People also ask

How do I find the shell output?

Get output from shell command using subprocess Launch the shell command that we want to execute using subprocess. Popen function. The arguments to this command is the shell command as a list and specify output and error. The output from subprocess.

How do I run a shell command 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.


2 Answers

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

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

Hope this helps.

like image 95
Ise Wisteria Avatar answered Sep 29 '22 04:09

Ise Wisteria


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.

like image 28
Chris McMahan Avatar answered Sep 29 '22 04:09

Chris McMahan