0

When I open bash and press the up arrow I see the last command I have typed. Continues presses of the up arrow will show a series of commands typed on the past.

How do I find one specific command from that list, instead of having to press the up arrow n times?

3
  • Try this lifehacker.com/… – user Feb 3 '19 at 8:20
  • As you are mentioning needing to press UpArrow a specific number of times, do you know that the command is n command back in the history? – Kusalananda Feb 3 '19 at 8:29
  • Using the history command is out of question? – Rui F Ribeiro Feb 3 '19 at 9:36
6

Press CTRL+R and start typing. Press CTRL+R again to get the next found.

0
2

You can use below command to find in .bash_history file

sed -n '/commandwhichyouwanttosearch/p' bash.history

example

Suppose if you want to search for ls command in .bash_history

history | sed -n '/ls/p'
0
2

This one has not yet been mentioned.

!start-of-command

e.g.

echo hello
ls
!echo
#finds echo hello
0
1

Instead of pressing UpArrow exactly n times, you would use

!-n

in the shell.

This would invoke the history expansion facility of the bash shell and would replace the expansion with the command n steps back in history (and execute it).

Example:

$ history
    1  ls
    2  ls
    3  ls
    4  history
    5  echo hello
    6  echo good night
    7  history
$ !-3
echo hello
hello

See the "HISTORY EXPANSION" section in the bash manual.

0
1

history + grep (or any other text searching command)

If you want to list all history entries containing string "foo": history | grep "foo"

history - shows all commands in the history buffer

grep "foo" - searches for lines containing the string foo, and you can also use regular expressions accordingly to manual of grep.


Reverse i-search

If you want to go back through history (like you did before with arrow keys) using ctrl+r is the way to go. Just press ctrl+r and start typing. You can press ctrl+r multiple times when the phrase is already typed and it will iterate back through matching history entries


Fuzzy Finder

This is my personal preference. Its solution is not vanilla out of the box, but I think it deserves some credit. You can install a fuzzy finder extension for bash and it will make searching for many things much more efficient (it replaces reverse i-search so ctrl+r is being used as a shortcut for searching in history).

Not the answer you're looking for? Browse other questions tagged or ask your own question.