4

Sometimes I'd like to get some command from history output, copy it to a bash prompt, make some changes and run it. Is there a way to copy a command from history output to a bash prompt without involving the mouse? For example, it would be some script that I can bind a shortcut to.

Maybe I do not understand fc enough, but it looks like I cannot select folders or files via fc (like Tab for usual command prompt)

5

you need to take a look at the bash fc command.

If you want to edit before rexecuting a history line just do like this

fc 123

where 123 is the history line number you see typing the command history.
It will open your favorite editor and allow you to modifiy the line then quit and save and it will run.

You can also do it a range of command like this:

fc 123 135

To work on command history from 123 to 135.

Edit 1:
if you need to run without edit consider watch the post Re-execute fc command from history

4

If you want to reexecute a command from your history, you can use ^r (ctrl + r) in your terminal. It's a reverse search which permits to retrieve a command and edit it before you enter it. I don't know if it works with other shell than bash. Though it's like one of the most useful thing I ever seen.

From the bash documentation :

reverse-search-history (C-r)
Search backward starting at the current line and moving ‘up’ through the history as necessary. This is an incremental search.

Here is the manual.

  • Yes that's also a possibility – Kiwy Feb 10 '14 at 9:26
  • 1
    It is useful if you want to execute only one command from your history. Your solution is better in case you want to execute multiple lines. Plus the ^r technique is useful because you don't actually have to know the line number in the history. – Depado Feb 10 '14 at 9:28
  • fc 'command begins… ' will find only the last line that started that way, invoke FCEDIT on the command, then run it. – mikeserv Mar 13 '14 at 18:34
0

Enter command number (like !1234) and press Alt+Shift+X. After that command with number 1234 will be printed in terminal prompt and this command is editable as usual.

copy_line_from_history_to_prompt () {
  READLINE_LINE=$( history -p "$READLINE_LINE" ) ;
}
bind -x '"eX": copy_line_from_history_to_prompt' # Alt+Shift+X

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.