sudo & root
sudo runs a single command with administrator (root) privileges.
Syntax
sudo commandThe root user can do anything on the system. Working as root all the time is dangerous, so instead you run individual admin commands with sudo ("superuser do").
How it works
Prefix any command with sudo and, after you type your password once, it runs with root privileges. Only users in the sudo (or wheel) group may do this.
sudo apt update— run one command as root.sudo -i— open a full root shell (use sparingly).sudo !!— re-run your previous command with sudo.
Example
# This fails: a normal user cannot write here
apt install nginx
# E: Could not open lock file - are you root?
# Run it as root instead
sudo apt install nginx
# Handy: repeat the last command with sudo
sudo !!When to use it
- A developer uses 'sudo apt install htop' to install a package without logging in as root.
- A sysadmin grants a junior engineer permission to restart nginx only with 'alice ALL=(ALL) NOPASSWD: /bin/systemctl restart nginx' in sudoers.
- A CI pipeline uses a dedicated service account with sudo rights for specific commands only, following the principle of least privilege.
More examples
Run a command as root
Shows sudo elevating privilege for package installation and file editing, and the handy 'sudo !!' shortcut.
# Install a package (requires root)
sudo apt install htop
# Edit a protected file
sudo nano /etc/hosts
# Run last command with sudo
sudo !!Run as a specific user
Uses sudo -u to run commands as a specific non-root user, useful for testing application permissions.
# Switch to another user's context
sudo -u www-data whoami
# www-data
# Run a command as the app service account
sudo -u deploy /opt/app/start.shConfigure limited sudo in sudoers
Shows how to use visudo to grant a user narrowly-scoped sudo access to a single command.
# Edit safely with visudo (validates syntax before saving)
sudo visudo
# Add this line to allow alice to restart nginx only
# alice ALL=(ALL) NOPASSWD: /bin/systemctl restart nginx
# Test the rule
sudo systemctl restart nginx
Discussion