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.