Key bindings for Bash history-search

Normally in Bash the up/down arrows will cycle through your most recent commands. This is all well and good, but sometimes the command you’re looking for is not in your recent history and you need to go searching for it. It would be nice if, for example, you could type ss, hit the up arrow, and have your most recent ssh command appear, even if it’s buried somewhere in your command history.

If this interests you, put the following in your .bashrc file:

bind '"\e[A":history-search-backward'
bind '"\e[B":history-search-forward'

This binds the up/down arrow keys to search through your history rather than your most recent commands — in other words, it’s like an autocomplete for your history. Bash doesn’t save your entire history, so it won’t search through every command you ever typed, only the most recent ones.

Some other helpful terminal things I found:

Ctrl+c: delete the current command and get a fresh prompt
Ctrl+e: move cursor to the end of the current command
Ctrl+a: move cursor to the beginning of the current command

Your mileage may vary, but I think these things are pretty useful.

Edit: People seem to recommend adding the following two commands below the key bindings in your .bashrc:

set show-all-if-ambiguous on
set completion-ignore-case on

…although I have yet to figure out when and whether this is helpful.

Advertisements

3 thoughts on “Key bindings for Bash history-search

  1. In this vein I’d also like to recommend the history command and the bang (!) operator, for instance:


    # history | grep ssh
    > 960 ssh mjw5407@assist.aset.psu.edu
    > 1000 history | grep ssh

    Then you can do

    # !960

    to repeat your ssh command. Also,

    # !!

    repeats the last command and

    # !ssh

    repeats the last ssh command.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s