Copy command from history to bash prompt
Solution 1
The following is a tmux
way.
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
Solution 2
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
Solution 3
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.
Related videos on Youtube
Loom
Updated on September 18, 2022Comments
-
Loom over 1 year
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 fromhistory
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 viafc
(like Tab for usual command prompt)-
S edwards about 10 yearsyou should take a look here : unix.stackexchange.com/q/104394/53092
-
mikeserv about 10 yearsfc 'command begins… '
-
-
S edwards about 10 yearsYes that's also a possibility
-
Depado about 10 yearsIt 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.
-
mikeserv about 10 yearsfc 'command begins… ' will find only the last line that started that way, invoke FCEDIT on the command, then run it.
-
Christian Herenz almost 3 yearsI would love to have this functionality, but I put the code in my ~.bashrc~ and start a new shell - but it does not work for me. Does it require a special Bash version?
-
Loom almost 3 years@ChristianHerenz - Yes, I use
tmux
and this command works with its infrastructure