Ubuntu Sudo Command Cheat Sheet

Get more Linux command cheat sheets at UbuntuFree.com

What is Sudo?

sudo allows users to run commands with elevated (superuser) privileges. It’s like “Run as Administrator” in Windows but much more flexible.

Basic Syntax

sudo [options] command

Example:

sudo apt update

Common Sudo Use Cases

Update & Upgrade:

sudo apt update && sudo apt upgrade

Install a Package:

sudo apt install nginx

Remove a Package:

sudo apt remove nginx

Restart a Service:

sudo systemctl restart apache2

Create Directory in Root:

sudo mkdir /protected-folder

Change File Ownership:

sudo chown john:john /var/www/html/index.html

Advanced Sudo Examples

Run as Another User:

sudo -u john ls /home/john

Preserve Environment Variables:

sudo -E env | grep USER

Run in Background:

sudo -b sleep 60

Edit sudoers File:

sudo visudo

Useful Sudo Options

-h: Show help message

-l: List allowed commands

-v: Extend session timeout

-i: Start root shell

-s: Run shell as superuser

-k: Expire cached credentials

--non-interactive : Avoid password prompts (useful in scripts)

Sudo Environment Variables

SUDO_USER: The invoking username

SUDO_UID : User ID of invoking user

SUDO_GID : Group ID of invoking user

SUDO_COMMAND : The last command executed

Pro Tips

Use sudo !! to rerun the last command with sudo.

Check logs:

sudo tail -f /var/log/auth.log

Allow passwordless commands for a user by editing sudoers:

john ALL=(ALL) NOPASSWD: /usr/bin/apt