Use `sudo !!` to Repeat a Command in Bash and Zsh.
Forgot sudo? Learn how sudo !! reruns your previous command in interactive Bash and Zsh shells, when it works, and how to check the command before it runs.
Ever run a command and realize it needed sudo?
In an interactive Bash or Zsh session, you can use !! to refer to the previous command:
$ sudo !!
The shell expands !! to the most recent command in its history, so the line becomes:
$ sudo command-you-ran-before
Example
Suppose you try to install a package without administrative privileges:
$ apt install nginx
After a permissions error, run:
$ sudo !!
The shell expands this to:
$ sudo apt install nginx
In many interactive shells, the expanded command is shown before it runs. If yours runs immediately, remember that !! executes the last history entry exactly as written, so check what that command was before using the shortcut.
Important notes
!!is shell history expansion, not a Linux command. It works in interactive Bash and Zsh sessions when history expansion is enabled; it may not work in scripts or other shells.- It repeats the previous command exactly. If that command was destructive or had the wrong arguments, adding
sudocan increase the consequences. - For many configuration files,
sudoshould be used with an editor, for examplesudoedit /etc/example.conf, instead of rerunning a command that writes through shell redirection. - To recall the previous command and edit it before running, press the Up arrow or use reverse history search with
Ctrl+R.
sudo !! is a quick way to rerun your previous command with elevated privileges in an interactive Bash or Zsh shell. Check the expanded command before it runs, especially when the command changes or deletes files.
We hope this was helpful.
Keep learning. Keep exploring. Stay secure.