Redirect Output to Buffers from Emacs Eshell

With Emacs eshell, you can redirect the standard output of shell programs into buffers:

echo "foo" > #<buffer my-buffer-name>

That will use existing buffers and create new buffers as needed. For me, the new buffers would not be switched to automatically, but created in the background.

You don’t pipe into a buffer function, but redirect the output like you’d redirect file output. Instead of a file on disk, you specify a buffer with the special form:

#<buffer ...>

This is the form you will see when you evaluate (current-buffer) and the buffer is converted to a string. So you may be used to reading, but not typing it.

Redirect Output to New Buffer and Show It

Writing and remembering that weird buffer naming form is not my cup of tea. And I usually want to see the result immediately. So here’s an alternative.

Redirecting the output also works similar to (insert)ing text into buffers. So you can redirect output to a buffer that is being returned from a function.

The new-buffer function name is not taken, so to make typing easier, I use that. Be advised that you should consider prefixing function names, though. I’ll personally take the risk.

This function will generate a new buffer called “untitled” – and thanks to generate-new-buffer will make sure to use an unused buffer name by appending “<1>”, “<2>”, … –, and switch to it immediately:

(defun new-buffer ()
  "Create and switch to new empty buffer named “untitled”, “untitled<2>”, etc."
  (switch-to-buffer (generate-new-buffer "untitled")))

Then use it like this in eshell:

echo "test" > (new-buffer)

I still intuitively want to use | instead of > to pipe to a function, not redirect the output, but that doesn’ work. You need to call the function to get the buffer object. Ah well; I still like it better than having to type the #<buffer ...> thing and type the buffer name, too!

Consider using shell-command

All of this makes sense if you’re in an eshell anyway, or craft complicated program pipes.

If you just want to execute a program once, and then get the output into a buffer, you can instead use the shell-command or async-shell-command that do exactly that.