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,246
  • 16
  • 81
  • 118
Trim
  • 251
  • 1
  • 3
  • 3

2 Answers2

34

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,246
  • 16
  • 81
  • 118
  • Thank you Dear friend, I edited bashrc file as you said, its now working. – Trim Oct 27 '13 at 09:23
  • 1
    @Trim if it solved your problem then you can mark the answer as solved by clicking the tick under the voting buttons so that it can help future visitors. – kiri Oct 27 '13 at 09:24
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,246
  • 16
  • 81
  • 118
Radu Rădeanu
  • 169,590