Executing previous commands with !
Executing previous commands is done with exclamation marks. There are various ways to use this trick, which we’ll look at now.
Re-running a command with the same arguments
The !
command will execute the last command with the previous arguments. For example, !ssh
will go back and find the last ssh
command you ran and execute it with the same arguments. You can use this to re-run commands that you frequently use with the same arguments, such as to quickly re-connect to the SSH server you connect to every day.
Prepending a command to something in your history
The !!
command will execute the last command you ran, but with some other command in front of it. This may sound strange, but it’s very useful for situations where you accidentally ran a command that requires root privileges without sudo
at the beginning.
apt-get install nginx # fails with a permission error
sudo !!
# this is the command that runs:
sudo apt-get...