Sudo last command

2 snippets in Bash & Linux

SHBash & Linux

Execute as Superuser

SH · Permissions & Ownership
Syntax
sudo [options] command
Example
sudo apt update
sudo -u postgres psql
sudo !!

Note sudo !! reruns the last command with sudo (great when you forget to prefix it). -u runs as a specific user. Sudo access is configured in /etc/sudoers (edit only with visudo, never directly). Your password is cached for a short time after the first entry.

History Expansion: !! and !$

SH · Shortcuts & Productivity
Syntax
!!        # last command
!$        # last argument of previous command
!n        # command number n
!string   # last command starting with string
Example
apt install nginx
sudo !!
# Expands to: sudo apt install nginx

mkdir /opt/new-app
cd !$
# Expands to: cd /opt/new-app

!grep
# Reruns last command that started with 'grep'

Note !! is indispensable when you forget sudo. !$ avoids retyping long paths. Use !:n to reference a specific argument (e.g., !:2 for the second). Add :p to preview without executing: !!:p shows what would run.

Frequently asked questions

How does Bash & Linux handle sudo last command?
Bash & Linux covers this with 2 copy-ready snippets on this page. The "Execute as Superuser" snippet in Bash & Linux uses `sudo [options] command`.
Which command does the Bash & Linux example use?
The "Execute as Superuser" snippet uses `sudo [options] command`, from the Permissions & Ownership section of the Bash & Linux cheat sheet.
What other Bash & Linux snippets are shown for "sudo last command"?
Besides "Execute as Superuser", this page also shows "History Expansion: !! and !$".
Is there anything to watch out for?
Yes. For "Execute as Superuser": sudo !! reruns the last command with sudo (great when you forget to prefix it). -u runs as a specific user. Sudo access is configured in /etc/sudoers (edit only with visudo, never directly). Your password is cached for a short time after the first entry.