I often find myself searching in my history by doing something like

history | grep searchterm

This returns a list of all the times that I used searchterm in a command. However, I would often like to know the n previous commands and the m next commands that I entered before and after that command which contained searchterm. Often the context in which I ran a command is very useful.

What I would like to be able to do is

> history-search-context searchterm n m

and get separated lists of commands that were entered n commands before and m commands after any history entry that contains searchterm.


> history-search-context mycommand 2 1

687 cd some/directory
688 ls -a
689 mycommand -flag arg1
690 touch file
943 apt-get install something
944 pwd
945 mycommand -otherflag arg1 arg2 arg3
946 rm file

This would tell me that I used mycommand twice in recorded history with some interesting flags and arguments, and within a window of [-2,+1] commands I had one time run it in some/directory and had to create a file, and the other time, I installed something, checked which directory I was in, and then deleted file.

Is there an existing way to do this? If not, how to accomplish this?

  • If my answer solved your problem, please accept it by clicking the checkmark next to it. Thank you! – Jeff Schaller Feb 17 at 13:45

I would approach it with a helper function and grep, since (GNU) grep has a natural set of options for "lines before & after the match". The bare-bones version is:

histgrep() {
  history | grep -B $2 -A $3 "$1"

... and you'd use it just like your history-search-context command above:

$ histgrep jeff 1 1

  517  vi go.sh
  518  x=jeff
  519  y=/tmp
  832  sudo visudo
  833  sudo adduser jeff2
  834  man sudoers
  841  sudo ls -al /var/lib/sudo/lectured
  842  sudo rm /var/lib/sudo/lectured/jeff /var/lib/sudo/lectured/schaller
  843  sudo ls
  940  ls *[[:digit:]][[:digit:]][[:digit:]][[:digit:]][[:digit:]]*
  941  touch jeff߄߅߆߇߈߉.txt
  942  ls
 1235  histgrep a b c
 1236  histgrep jeff a 1
 1237  histgrep jeff 1 a
 1238  histgrep jeff 1 1

After adding some basic error-checking the function would be:

histgrep() {
  if [ "$#" -ne 3 ]
    echo "Usage: histgrep searchterm n-before m-after"
  case "$2$3" in
        echo "Usage: histgrep searchterm n-before m-after"
  history | grep -B $2 -A $3 "$1"

You could easily enough name it history-search-context instead of histgrep if you wanted:

history-search-context() {
# ...
  • This is exactly what I was looking for. Perfect. Thanks so much for the solution. – user10108 Feb 10 at 21:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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