Using bash history to get a previous command, copy

2019-03-07 15:37发布

Just a question to improve my bash skills. I always do this:

$ history | grep some_long_command

...
...
123 some_long_command1.........
124 some_long_command2.........
...

I can then run the command the command I found by doing:

!123

However, I often want to do this:

some_long_command1foobar

I.e. change the command before I run it. Can you use bash to run this command instead:

#some_long_command1

so it gets commented.

Then I don't have to use my mouse to highlight the command, edit it and then run it (I can just use the keyboard - faster).

I suppose I could write a script to do it but there might already be functionality built in somewhere....?

Thank you.

10条回答
Fickle 薄情
2楼-- · 2019-03-07 16:20

Instead of using the history command, bind history-search-backward/history-search-forward to key shortcuts which can be remembered easily (I prefer PgUp/PgDown). To do that, put this into your .inputrc file:

"<key code>":  history-search-backward
"<key code>":  history-search-forward

To get <key code>, type Ctrl-V <key> in the shell, and replace the starting ^[ with \e in whatever was output.

After this is set up, you can just type some and press PgUp to get some_long_command. If you need some_long_command with_some_arg but there is a similar command some_long_command with_some_other_arg later in the history, you can cycle through until you reach it by typing some and then hitting PgUp repeatedly, or you can type some, hit PgUp, move the cursor to where the two commands start to differ, type a few characters and hit PgUp once more. This ability to quickly page through / differentiate between similar commands makes it in my opinion a much more comfortable tool than Ctrl-R.

查看更多
在下西门庆
3楼-- · 2019-03-07 16:27

You can also put

shopt -s histverify

in your .bash_profile, which causes any history expansion to appear on your command line without running it, allowing you to edit before doing so.

查看更多
Rolldiameter
4楼-- · 2019-03-07 16:28

Put

alias r='fc -s'

in your .bashrc (home dir) then you can just type in

r <whatever>

at the command prompt and you will execute a copy of the last <whatever> command (same params) that is in your history. just hit up arrow to see what you have executed if you feel the need.

查看更多
The star\"
5楼-- · 2019-03-07 16:34
!123:gs/old/new/

Will run command 123 replacing the string 'old' with the string 'new'.

查看更多
登录 后发表回答