A Better History Command

htv2012

Hai Vu

Posted on October 10, 2023

A Better History Command

Problem

Many people using the Linux terminal repeatedly search the command line history with such command:

history | grep cd
Enter fullscreen mode Exit fullscreen mode

While this command is fine, I would like to shorten the command.

Design

I would like to create a command h which will

  • List the history if there is no argument
  • Search the history for the arguments when they are supplied

Implementation

After a few trials and error, I finally came up with a shell function, which I add to my ~/.bashrc and ~/.zshrc files:

function h() {
    history | grep -E --color=auto "${@:-}"
}
Enter fullscreen mode Exit fullscreen mode

Usage

When invoked without any arguments, the command h behaves just like the history command.

When invoked with one or more arguments, those arguments will be passed on to the grep command. Examples:

h            # shorthand for history
h ls         # Searches history for the ls command
h -i myfile  # Case-insensitive search for myfile
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
htv2012
Hai Vu

Posted on October 10, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related