25

How can I configure the key to get commands from history?

Example: If I type p and press then it should only show commands in the history starting with "p" like python, php, perl, etc.

Please can anyone help me to configure this feature?

I've edited .bashrc, but it doesn't work for me.

kiri
  • 28,986
Trim
  • 251

2 Answers2

36

Both methods below are almost equivalent, it just depends on which file you want to edit. I'd recommend .bashrc myself, as it doesn't involve editing a local copy of a system file.

If you experience any problems with this, please comment below so that it can be fixed.

Using ~/.bashrc

  1. Edit ~/.bashrc with this command:

    gedit ~/.bashrc
    
  2. Add the following lines:

    bind '"\e[A": history-search-backward'
    bind '"\e[B": history-search-forward'
    
  3. Save then close the file.
  4. Execute this command in a terminal:

    source ~/.bashrc
    

Using ~/.inputrc

  1. Execute this command in a terminal:

    cp /etc/inputrc ~/.inputrc
    
  2. Edit the new ~/.inputrc file with this command:

    gedit ~/.inputrc
    
  3. Append these lines to the file:

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

References:

kiri
  • 28,986
4

As alternative, you can press Ctrl+R then start typing the command or any part of the command that you are looking for. You'll see an auto-complete of a past command at your prompt. If you keep typing, more specific options will appear. You can also press Ctrl+R again as many times as you want to, this goes back in your history to the previous matching command each time (source: Navigating Bash History with Ctrl+R).

Another suggestion, if you want to find, for example, the last 5 commands from your history starting with "p", you can use the following command:

grep "^p" ~/.bash_history | tail -n 5
kiri
  • 28,986
Radu Rădeanu
  • 174,089
  • 51
  • 332
  • 407