Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

zsh-like history in bash

Tags:

bash

zsh

I really like zsh's history autocomplete feature. Namely, when I press up, I get the previous command. When I type emacs and press up, I get the last emacs command I used. When I type git and press up, I get the last git command I used. When I try to do this in bash, it just goes to the last generic command I used. Essentially, I want to be able to half-type a command and press up to get the last command I used that matches what I've typed so far. I don't know how to achieve this in bash. I can't use zsh on this system, so is it possible to replicate this functionality in bash?

like image 519
Hal T Avatar asked Feb 17 '17 13:02

Hal T


2 Answers

The up arrow is bound to the previous-history command. You want to rebind it to history-search-backward (which is unbound by default) instead. You can check which keys previous-history is currently bound to:

$ bind -p | grep previous-history
"\C-p": previous-history
"\eOA": previous-history
"\e[A": previous-history

In my case, the last two both represent up arrow (the exact escape sequence may differ from terminal to terminal, or depending on what mode the terminal is in, but these two are fairly standard). Especially since previous-history will still be available with Control-P, it's safe to change the behavior of the up arrow.

Add this to your .inputrc file (creating the file if necessary):

"\e[A": history-search-backward
"\eOA": history-previous-history

Or, you can add call bind from your .bashrc:

bind '"\e[A": history-search-backward'
bind '"\eOA": history-previous-history'

You may also want to similarly bind history-search-forward to the down arrow key, \e[B and \eOB.

like image 139
chepner Avatar answered Oct 21 '22 10:10

chepner


You can search your history with ctrl+R.

When you first press it, the prompt will change and you will be able to enter the characters you want to search for in the history. The new prompt disregards characters that were entered in the previous prompt and will overwrite them when something from the history is matched.

It will display the last command that matches your input and you can press ctrl+R again to navigate the results from the latest to the earliest.

When you've found the entry you're interested in, you can either press Enter to execute it or the left or right arrows to return to the standard prompt to edit the command line. Pressing the up or down arrows will return to the standard prompt but navigate the history one step forward or backward, which I find more confusing than anything.

like image 32
Aaron Avatar answered Oct 21 '22 10:10

Aaron