! syntax example in bash

Let's have this command:

$ head /etc/passwd /etc/crontab /etc/services
# more output
Repeat latest command:
$ !!
head /etc/passwd /etc/crontab /etc/services
Use latest command as parameters for other command:
$ echo !!
echo head /etc/passwd /etc/crontab /etc/services 
head /etc/passwd /etc/crontab /etc/services
Use 2nd parameter from previous command in another command. Count starts from 0:
$ vi !:2
vi /etc/crontab
Use first argument from the previous command:
$ vi !^
vi /etc/passwd
Use last argument from the previous command:
$ vi !$
vi /etc/services
Repeat the nth command from your history.
It counts from the top:
$ !10
Repeat the nth command from bottom of your history.
Counts from the bottom:
$ !-10
Repeat the last command matching a string’s beginning.
The bang (!) followed by the first character (or string) matching the command you want to run will repeat the most recent instance of that command:
$ !ma
mail
Repeat the last command matching anywhere in a string.
The !?<string> format does the same as the above, but <string> doesn’t have to be at the beginning of the command
$ !?links
vi ../links.txt
Repeat but substitute a string.
String substitution allows to rerun the commands with the new values. Here is an example:
$ head /etc/passwd
# head output
$ !!:s^passwd^crontab
head /etc/crontab
So, it will replace passwd with crontab.
You can even do the same with !<string>:s^<old>^<new>:
$ !he:s^passwd^crontab
head /etc/crontab
Print out commands.
Sometimes you might want to print out the command, but don’t want it executed. You can accomplish this task with !:p:
$ !!:p
head /etc/crontab
$ head /etc/crontab
# command output
$ !h:p
head /etc/crontab