Last Updated: May 11, 2021
·
614
· ajnasz

Use your history!

If you haven't read the history expansion part of your shell's manual, here I will show some ideas why should do it.

However I read it and I found it super useful, I never got used to it, but few days ago I opened it again and started to practice it.

I'm working on ZSH but these commands should work on Bash (and probably on other shells) too.

Love !

By default, you say to the shell to use the history expansion by typing !. Starting a line or a command argument with ! you can send special commands to your shell.

Find commands

Let's imagine you want to list the files in /etc/apt

$ ls /etc/apt

Then you want to see it's content again

$ !!

Yay! Typing another ! after the first ! will refer to the last command in your history.

To list the /etc/apt/sources.list.d directory, you can use the command above:

$ !!/sources.list.d

Referring by it's number

You can refer to the n-th command by typing n after the first !

$ !1

It will refer to you first command in your history, in this case it will be ls /etc/apt

$ !2

And this will expand to ls /etc/apt/sources.list.d

To refer to the current command-line minus n use negative numbers:

$ !-1

It's the same as !!

$ !-2

It will call the second last command.

Search by command

By typing the command name after !, the shell will search for the most recent history entry starting with this command:

$ !ls

Will find the ls /etc/apt command

You can also use only a part of the command:

$ !conv

It will find the convert command for example if you used it before.

Search for command contains a string

$ !?etc

That will expand to ls /etc/apt

Manipulate your history entries

You can do much more things with your history
entries in addition to repeating them.

You can use modifiers by typing a :modifier after the !search command. You can use more then one modifiers!

Example:

$ !ls:$:h

This will first expand the expression we have seen before then change it's output.

Referring to arguments

You can refer to the last argument by passing a $ sign after the :.

ls /etc/apt
!:$

That will print /etc/apt

Now we can use it do a quick move into the directory:

ls /etc/apt
cd !:$

Using command !:n you can refer to the n-th argument

ls /etc/apt /etc/apt/sources.list.d
cd !:1

The !:1 will expand to /etc/apt so, you will go to the /etc/apt directory. By saying cd !:2 you would go to the /etc/apt/sources.list.d directory.

Just the beginning

That's just the beginning, you can find much more in the manual of your shell or online.

ZSH
or
Bash

Practice as much as you can and have a new habit!

2 Responses
Add your response

Thank you ,simple useful skill

over 1 year ago ·

I use this in my bash_login (mac) to type a partial search and use the arrow keys (up and down) to search through the history related to the partial:
bind '"[A":history-search-backward'
bind '"[B":history-search-forward'

over 1 year ago ·