Terminal & Shell

Make Up Arrow Search Your Previous Terminal Commands

Abhishek Ghimire · 2 min read
14 views

If you use the terminal regularly, you probably press the Up Arrow to find a command you used earlier.

By default, pressing ↑ goes through your command history one command at a time. This can become annoying when you have a long history.

For example, if you type:

git

and press , you may get an unrelated command instead of your previous Git command.

A small shell configuration can make this much better.

What We Want

After this setup, if you type:

git

and press , it will search through your previous commands that start with git.

For example:

git status
git add .
git commit -m "update"
git push

Similarly:

ssh

then ↑ can find previous SSH commands such as:

ssh abhishek@192.168.1.1
ssh user@192.168.1.1

This is a small change, but it can save a lot of time when working in the terminal.


For Bash

Bash uses Readline for command-line editing, and its configuration is stored in:

~/.inputrc

Open the file:

nano ~/.inputrc

Add:

"\e[A": history-search-backward
"\e[B": history-search-forward

Save the file and apply the changes:

bind -f ~/.inputrc

Now try:

git

and press .

Bash will search through commands beginning with git.

This works on Linux and also works if you are using Bash on macOS.


For Zsh

macOS uses Zsh by default, and many Linux users also use Zsh.

Zsh does not use .inputrc, so the configuration needs to go into:

~/.zshrc

Open it:

nano ~/.zshrc

Add:

autoload -Uz up-line-or-beginning-search
autoload -Uz down-line-or-beginning-search

zle -N up-line-or-beginning-search
zle -N down-line-or-beginning-search

bindkey '^[[A' up-line-or-beginning-search
bindkey '^[[B' down-line-or-beginning-search

Then reload your Zsh configuration:

source ~/.zshrc

Now try:

ssh

and press .

It will search your previous SSH commands.


Which File Should You Edit?

It depends on the shell you are using.

You can check your current shell with:

echo $SHELL

For example:

/bin/bash

means you are using Bash.

If you see:

/bin/zsh

you are using Zsh.


Linux and macOS

This setup works on both operating systems. The important thing is which shell you are using, not the operating system.

For example:

Linux + Bash

~/.inputrc

Linux + Zsh

~/.zshrc

macOS + Zsh

~/.zshrc

macOS + Bash

~/.inputrc

So before changing anything, check:

echo $SHELL

A Small Change With a Big Difference

Instead of repeatedly pressing ↑ through unrelated commands, just type the beginning of the command you want.

git  + ↑
ssh  + ↑
docker + ↑
npm  + ↑
python + ↑

It makes the terminal feel much faster, especially if you frequently work with the same commands.

Once you get used to it, going back to the default Up Arrow behavior feels surprisingly slow.

Written by

Abhishek Ghimire

Writes here about engineering, technology, and the things worth building.