Patricio Treviño · 29 August, 2018 · 2 min read
Using the bang command (!)
The bang command allows you to not only quickly retrieve several most
recent commands, but also reuse parts of the previous command (or any other
command within the bash history), thus making command chaining more easy to
implement and even more powerful.
Syntax
Option
Description
!
Use the last command
[n]
Use the n-th unique command in the history
-[n]
Use the command n-th lines back in the history (can be repeated commands)
[str]
Use the most recent command that starts with the given string
?[str]
Use the most recent command that contains the given string
:0
Use the previous command with no arguments
^
Use the first word of the previous command
:[n]
Use the n-th word of the previous command
$
Use the last word of the previous command
*
Use the all words of the previous command
:p
Prints the matching command without executing it
Example
$ cd /
# try to create test in /
$ mkdir test
mkdir: test: Permission denied
# execute the last command adding sudo
$ sudo !!
sudo mkdir test
# execute the last command replacing test for test2
$ sudo ! :1 test2
sudo mkdir test2
References
Bang command