Command-Line Bash History – Put History Command onto Command Line Without Executing It

bashcommand historycommand line

I use !n where (n) is the line number for executing a line in the history file I want executed at the command prompt which I find via history|less.

But there is a command line history event I wish to manually modify. How can I insert into the command line a history events contents without it actually executing so I can modify and then press return?

Best,

Best Answer

To request that the command be printed rather than executed after history substitution, add the :p modifier, e.g. !42:p. The resulting command will also be entered in the history, so you can press Up to edit it.

If you have the histverify option set (shopt -s histverify), you will always have the opportunity to edit the result of history substitutions.

The fc builtin gives limited access to history expansion (no word designators), and lets you edit a previous command in an external editor.

You can use !prefix to refer to the last command beginning with prefix, and !?substring to refer to the last command beginning with substring. When you know what you're looking for, this can save a lot of time over history | less.

Another way to search through previous history is incremental search: press Ctrl+R and start entering a substring of what you're looking for. Press Ctrl+R to go to the previous occurence of the search string so far and Ctrl+S if you've gone too far. Most keys other than Ctrl+R, Ctrl+S, Backspace and ordinary characters terminate the incremental search and have their usual effect (e.g. arrow keys to move the cursor in the line you've reached, Enter to run the command).

Related Question