How do I get the output of
(shell-command "df") (or some other more complex command, that I don't want to retype often) in the current buffer?
I run it by typing
C-c p after it, but then it opens another buffer and sends the output there.
Emacs Stack Exchange is a question and answer site for those using, extending or developing Emacs. It only takes a minute to sign up.Sign up to join this community
Actually the shortest way of doing it is to use
shell-command with a prefix argument. This is mapped to
C-u M-!. The
C-u prefix argument changes the standard
M-! to insert the output in the current buffer instead of just echoing it in the messages buffer. So, the full command for the df example is
C-u M-! df RET
C-u M-| that Emacs User is describing, is actually
shell-command-on-region which is a very cool command, too. You can use it e.g. to do a word count on the current selected region. It is even more useful with the prefix argument, because then the current region is replaced by the output of the shell command. I e.g. use this to pretty format an XML buffer by selecting the whole buffer and then using
C-u M-| xmllint --format - RET
to replace the whole buffer with the output from xmllint.
Here's a very simple function that will insert the shell command's output at point it the current buffer. Note that it makes no effort to do error checking, but you can adapt it to do so if needed:
(defun insert-shell-command-output (command) "Get shell COMMAND output and insert it at point in current buffer." (insert (shell-command-to-string command)))
M-: (insert-shell-command-output "echo 'puppies'")
You can use this function as the basis for an interactive command, and then bind that command to a key, once you know which shell command you'd like to run over and over again:
(defun insert-puppies-output () "Insert my command output into the buffer." (interactive) (insert-shell-command-output "echo 'puppies'"))
If you want to do this without installing any more functions or customizing exiting ones or tweaking init file, try this:
C-u M-| df RET
df is the shell command you want run. The output of
df is inserted in the currently active buffer (and not the echo area) because of the
C-u prefix. Also note no quotes around the shell command, which makes it quicker to type and execute.
shell-command-on-region, it does not require a region to be active when calling this command. But it also works when you need to send a region as well. In that sense, doubles as
Since you don't want to retype long commands, you can cycle through previous shell commands with
C-u M-| M-p
If you didn't actually need a feature of the shell, you could also do this:
(call-process "df" nil t nil "-h")
The 't' is what tells it to insert into the current buffer. I added the '-h' to show where the args go. You can add more.