brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: sudo !! reruns your last command with sudo

Shell
~/tips/tip-shell-sudo-bang-bang

sudo !!

Reruns the previous command with sudo in front of it, so you do not retype it.

You type a long command, press Enter and get “permission denied”. I know the feeling, and I used to just retype the whole thing. Bash has a shortcut for exactly this moment.

!! is history expansion. Before Bash runs a line, it replaces !! with the previous command. Put sudo in front and you get the same command, now with root rights.

$ apt update
E: Could not open lock file - Permission denied
$ sudo !!
sudo apt update

Bash prints the expanded line before it runs it, so you can see what it is about to do. That matters, because it also works for commands you would rather not repeat blindly.

The caveat: history expansion only happens in interactive shells, and not inside single quotes. It does not work in scripts at all. Also look at the expanded line before you trust it, since sudo !! runs whatever was last, even if that was something destructive you ran by accident.

If you want to check first without running, add :p and Bash only prints it: !!:p. Then press the up arrow to edit it.

Further reading: Bash manual: History Interaction, Bash manual: Event Designators, On this site: Alt+. pastes the last argument of your previous command, On this site: cp file{,.bak} makes a backup copy without typing the name twice

More Shell tips zmv -n '(*).log' '$1.txt' zoxide query -ls project f=$(mktemp --suffix=.json) shopt globskipdots echo $EPOCHSECONDS All Shell tips (78) All topics

Link