Bash – How to recall a numbered history command for edit

bashcommand history

I frequently search for changes with history | grep 'string'

I get a list of commands in my history, along with the history line number), e.g.

history | grep 'git'

  755  git status
 1535  git push origin master
 1570  git merge origin/one-146
 1667  git reset --hard origin/master

I can now recall and execute a command in one go with !nnn, for example:

!755
git status
# On branch master
nothing to commit, working directory clean

My question is: How can I recall a numbered history command and stay on the command line for editing and not execute it right away 'as is', the way that ! does, so that I can change a couple of things before pressing the return key?

Best Answer

I've since adopted another approach to this - using ![line-number]:p

This prints the statement and adds it to history but doesn't actually execute it. I then do up arrow and change it as desired.

I combine this with my hg alias (alias hg='history | grep ') to recall history commands based on some text.

Example:

$ hg checkout

17140   git checkout README.rdoc
17143   git checkout master
17201   git checkout README.rdoc
17204   git checkout master
17923   git checkout .bashrc
18151   git checkout v311

I use this in addition to ctrl-r (reverse history search) because sometimes I prefer to see an immediate list of all the possibilities for a given string rather than just the output on 1 line that ctrl-r shows. After hg [string] I would then do ![line-number]search_string as in the hg checkout shown above.

Related Question