How to copy a previously entered command using the history utility without running it again?

Solution 1:

How about, put this on your command line:

$ !372

Then press ESC followed by CTRL+E. This will autoexpand on the command line without actually running it. (also expands everything else on the line, including env vars)

This only works on Bash, as far as I'm aware.

Solution 2:

You could use Ctrlr and then type some characters from the original command e.g.

(reverse-i-search)`/etc': sudo /etc/init.d/apache2 restart

above I typed Ctrl-r /etc and it pulled up the sudo /etc/init.d/apache2 restart command from the history

Solution 3:

history | grep 372 should work, right?

Edit:

Additionally you could do something like echo !372 > /dev/clip to put the command directory into your clipboard.

Solution 4:

MDMarra gave the easy way (history|grep and copy/paste using your desktop environment, assuming you have one). I'll provide what I call the hard way, which works if you don't have a desktop environment or a mouse.

Assuming you're running bash as your shell:

$ set -o vi
$ ESC372k

(you'll now have the command you ran 372 commands ago, on the line, and you'll be in vi-style command mode. Edit as you would if you were using ex/vi)

Solution 5:

The simplest and quickest way to do what you want is to run:

!372:p

followed by Enter and