2

How can I run bash scripts from emacs and show the result in emacs?

4 Answers 4

4

Did you try the shell-command command? If you don’t know what it does, run C-h f shell-command to see the help for it:

shell-command is an interactive and byte-compiled function defined in
simple.el.gz.

Signature
(shell-command COMMAND &optional OUTPUT-BUFFER ERROR-BUFFER)

Documentation
Execute string COMMAND in inferior shell; display output, if any.

With prefix argument, insert the COMMAND's output at point.

Interactively, prompt for COMMAND in the minibuffer.
2

Type M-x shell and enter your command.

In addtion to M-x shell-command, there is also shell-command-on-region which will pipe the Emacs region into your command and output the results to the Messages buffer.

1

A fun and esoteric way to see the output of a program in emacs is to use Eshell Redirection.

  1. M-x eshell - Start up eshell
  2. ls /usr > #<buffer *scratch*> - Redirect the output of ls /usr to the *scratch* buffer.
  3. C-x b *scratch* - Switch to the *scratch* buffer to verify the output.
1

You can also run bash scripts from an Org mode file using babel. Add something like this to your Org mode file:

#+begin_src shell
date
#+end_src

Pressing C-c C-c on the source block runs the script, producing the following output:

#+RESULTS:
: Fri Oct 28 10:14:18 AM EDT 2022

It can be an arbitrary script, e.g. create a /tmp/my-script file like this:

#! /bin/bash

echo "This is the output of my script"

then make it executable with chmod +x /tmp/my-script and then add the following source block to an Org mode file:

#+begin_src shell
/tmp/my-script
#+end_src

Pressing C-c C-c on the source block produces the following output:


#+RESULTS:
: This is the output of my script

You can read about source blocks in Org mode in the manual with C-h i g(org)RET m Working with source code RET.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.