DEV Community

Cover image for A Better History Command
Hai Vu
Hai Vu

Posted on

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

Top comments (1)

Collapse
 
dothtm profile image
dotHTM

I really appreciate the fish shell’s history command and completions.