Skip to content
Go back

How to make searching shell history faster with a custom zsh function

| Edited: Today

I frequently search my shell history for variations of the same commands. On macOS with zsh, that usually looked like this:

history | grep "sqlite3 ./data/pipeline.db"

Or, if I wanted to narrow it further:

history | grep sqlite3 | grep pipeline.dd | grep forecast

Typing this over and over got old quickly. So I added a small helper function in my ~/.zshrc:

h() {
  local cmd="history"
  for term in "$@"; do
    cmd="$cmd | grep --color=always \"$term\""
  done
  eval "$cmd"
}

Now I can just type:

h sqlite forecast

and get back results like:

 6528  sqlite3 data/pipeline.db '.mode line' 'select * from forecasts'
 6537  sqlite3 data/pipeline.db '.mode line' 'select count(*) from forecasts'
 6539  sqlite3 data/pipeline.db '.mode line' 'select * from forecasts' | less
 6549  sqlite3 data/pipeline.db '.mode line' 'select * from forecast_adjustments'

The function accepts multiple search terms, applies them in order, and still lets me pipe into other commands if needed:

h sqlite forecast | tail -n 5

Share this post on:

Next Post
Mobile App Vulnerabilities in ICS: What CISA Alerts Reveal