Skip to content

sudo Command Cheat Sheet

sudo (superuser do) allows a permitted user to execute a command as the superuser or another user, as specified by the security policy (/etc/sudoers).


Synopsis

sudo [options] command

Basic Usage

Run as Root

sudo apt update
You are prompted for your own password.

Login as Root (Interactive)

sudo -i
Simulates a login shell for root (similar to su -).

sudo -s
Runs a shell specified by the $SHELL variable.


User Switching (-u)

Run a command as a user other than root.

sudo -u postgres psql
sudo -u www-data php script.php

Editing Files (SAFE WAY)

Don't use sudo nano file. Use sudoedit.

sudoedit /etc/hosts
or
sudo -e /etc/hosts

Why? 1. It copies the file to a temporary location. 2. Opens your editor as your user (preserving your config/plugins). 3. Copies it back as root upon save. 4. More secure (editor doesn't run with root privileges).


Credential Caching

Validate credentials (-v)

Refreshes the cached credential timestamp (usually 15 mins).

sudo -v

Kill credentials (-k)

Invalidates the user's cached credentials. Next sudo will require a password immediately.

sudo -k

Other Options

Background Execution (-b)

Run the command in the background.

sudo -b long_script.sh

Pass Environment Variables (-E)

Preserve current environment variables.

sudo -E python script.py

Stop "Stdin is not a tty" error (-S)

Read password from standard input (Useful for scripts, usually discouraged for security).

echo "password" | sudo -S command

Configuration

Sudo is configured in /etc/sudoers. ALWAYS edit using visudo. It checks for syntax errors before saving.

sudo visudo

Allow User to Run Without Password

In /etc/sudoers:

username ALL=(ALL) NOPASSWD: ALL


Notes

  • Difference from su: su switches the user. sudo grants privileges for a single command (mostly).
  • Listing privileges: Run sudo -l to see what commands you are allowed to run.