Insert the output of shell command into emacs buffer

I want to set a key binding to insert the date into the buffer. I have written the following lisp in my .emacs file. Using date as an example:

;;put the date                                                                  
(global-set-key
 (kbd "C-c C-d")
 (shell-command "date" (current-buffer))
)

The key binding works okay when I use other commands like 'next-line, but shell-command will put it into the *scratch* buffer when the .emacs is read and leaves it at that.

Maybe I need to use shell-command-on-region.


Solution 1:

For the general case of inserting any output of a shell command to the current buffer, you can use the in-built keyboard chords:

C-u M-! <shell-command>

which runs the same shell-command function, and also inserts the output back at the point in the current buffer.

The entire key-stroke itself can be saved as a macro (and perhaps assigned to a shortcut) for easier invocation of common shell commands.

Solution 2:

A friend of mine at work helped me.

(defun put-the-date ()
  (interactive)
  (insert (shell-command-to-string "date")))

(global-set-key
 (kbd "C-c C-d")
 'put-the-date
 )