sudo
Overview
sudo runs a command as another user (default: root) according to policy in /etc/sudoers and /etc/sudoers.d/*. Prefer it over lingering in a root shell.
Syntax
sudo [options] [command]
sudo -i
sudo -u user command
sudoedit fileCommon Options
| Option | Description |
|---|---|
-u user |
Run as user (not root) |
-i |
Login shell as target user |
-s |
Shell as target user |
-E |
Preserve environment (policy permitting) |
-k |
Invalidate cached credentials |
-l |
List allowed commands |
-n |
Non-interactive (fail if password needed) |
-v |
Validate/extend timestamp |
-e / sudoedit |
Edit file safely as root |
Key Use Cases
- Administrative package and service changes
- Least-privilege elevation per command
- Audited privileged actions (via logs)
- Safe file edits as root
Safety
Never chmod sudoers to world-writable. Always edit with visudo. Beware sudo pipelines: sudo cat file | grep x only elevates cat. Use sudo sh -c '…' when the whole pipeline needs root.
Examples with Explanations
Run one admin command
sudo apt update
sudo systemctl restart nginxElevates only those processes; returns to normal user after.
Edit a system file
sudoedit /etc/hosts
# or: sudo -e /etc/ssh/sshd_configCopies to a temp file and installs only if edit succeeds — safer than sudo vim quirks.
Shell as root
sudo -iFull root login environment when many admin steps are needed; exit when done.
Run as another service user
sudo -u www-data ls /var/wwwDebug permissions as the app user.
See your privileges
sudo -lShows what policy allows for your account.
Pass env var explicitly
sudo ENV=prod /usr/local/bin/deployPrefer explicit vars over blanket -E.
Notes & Pitfalls
- Credential cache is typically ~15 minutes per tty;
sudo -kclears it. - Ubuntu ships an admin group (
sudo) with broad rights via sudoers. - Logs:
journalctl -u sudoor/var/log/auth.logdepending on distro.