Bash Bang Commands

This is a rehash of an article I’ve been meaning to read more thoroughly, and only the commands and parts I’m not already familiar with. Restated in my own words, but I’ve linked the original article below, as it’s much more thorough.

The Double Shot !!

Use !! to run the last command again. I knew this, but only in the context of sudo !!.

A Shot in the Dark !?

Use !? to repeat a matching command in history where any part of the string matches. For example,
$ terraform apply 
$ !?apply

Hold the cream !!:s^old^new (substitute a misspelling)

Possibly more typing than it’s worth, but maybe better when used as a macro.
$ echo hello
$ !!:s^hello^bye
OR with a matching command
$ ls -al
$ !l:s^-al^-alh
OR just from the last command
$ echo hi
$ ^hi^hey

Repeat from argument number

I use $_ the most from this, which is the last argument sent to a command. The nicest use I find is with systemctl.
$ systemctl enable --now myamazingservicename.service
$ systemctl status $_
From the article, we can also specify the argument from the last command using !:1, the command is 0 and each argument after adds 1. I can’t think of a time I’d really use this, but there is a possible, but maybe it’s to cd into a lot of nested directories you just made quickly.
$ mkdir -p /dir/place/here/folder/path
$ cd !:2
If you want to use a command in the history, rather than the last one, just do:
$ ssh place 
$ ssh !ssh:1

Decaf Print (don’t execute) previous

$ !:p 
$ !ls:p

References

Strongly referenced from: #binbash #bash