Is there any way to execute commands from history?
In bash, just !636
will be ok.
Yes, it's called "history expansion." See
LESS='+/^HISTORY EXPANSION' man bash
for full details.
Using an exclamation point followed by a number is arguably the simplest use:
!636
However, you can also run the last executed command directly without knowing its history number:
!!
Or you can run two commands back:
!-2
The form I most often use, however, is to repeat the last argument of the last command:
echo this text goes into a file > /tmp/afile.txt
cat !$
Or, let's say I'm inspecting a file. Using tab completion, I might do the following:
ls -l /really/long/path/to/some/file
less !$
Again, read the man page for more details:
LESS='+/^HISTORY EXPANSION' man bash
A nice one, if you don't want to first history, note the number, etc:
in bash (and maybe others):
ctrl-r something
(ctrl-r
= "reverse search interactively") (something
= a part of a previous command)
This will show you the latest history line containing something
. To get the one before, do ctrl-r (alone) again, each time it gets a previous line.
ex:
ctrl-r 10
to show the latest history line containing '10' (for exemple the line with $10
, in your exemple), and ctrl-r
again until you retrieve the history line you were looking for
When the line you wanted appear, just Enter
to run it (or you can also edit it, using the arrow keys
, backspace
, and ctrl-a
to go to the beginning of the line, ctrl-e
to get to the End, ctrl-k
: to "kill" from cursor to end of line (=deletes+saves it in a buffer), ctrl-y
: to restore, from the buffer, a previously killed bit, etc.)
If you want to search forward (ctrl-s), you first need to disable XON : see https://stackoverflow.com/a/791800/1841533 :
" just to disable XON/XOFF by running
stty -ixon
" (and then you will be able to use ctrl-s, without having it freeze the terminal)