Linux sudo Command

SuperUser DO - 10 Practical Examples with Detailed Explanations

Example 1

Execute Command as Root

$ sudo apt update
[sudo] password for user: 
Hit:1 http://archive.ubuntu.com/ubuntu jammy InRelease
Get:2 http://security.ubuntu.com/ubuntu jammy-security InRelease [110 kB]
Fetched 2,345 kB in 3s (780 kB/s)
Reading package lists... Done
Executes a command with root (superuser) privileges. The most common use of sudo. You'll be prompted for your password (not the root password), and if you're authorized in the sudoers file, the command runs with elevated privileges. Essential for system administration tasks.
Security: sudo is safer than logging in as root - it provides accountability and limits privilege escalation
Example 2

Run Command as Different User

$ sudo -u postgres psql
psql (14.5)
Type "help" for help.

postgres=#
Executes a command as a specific user using the '-u' option. This is extremely useful for running commands as service accounts like postgres, apache, or mysql without switching users. Default is root if -u is not specified.
Use Case: Essential for database administration and managing service-owned files
Example 3

Open Root Shell

$ sudo -i
[sudo] password for user: 
root@hostname:~# 
Opens an interactive login shell as root using the '-i' option. This simulates a full root login with root's environment variables and working directory. Useful when you need to run multiple commands as root, but use with caution.
Caution: While in root shell, every command runs with full privileges. Exit promptly when done!
Example 4

Execute Shell as Root (Preserve Environment)

$ sudo -s
root@hostname:/home/user#
Opens a root shell using the '-s' option but preserves the current environment and working directory. Unlike '-i', this doesn't change to root's home directory or reset environment variables. Useful when you need to stay in your current location while having root privileges.
Difference: -s preserves environment, -i gives clean root environment
Example 5

Edit File as Root

$ sudo -e /etc/hosts
# Opens file in your default editor with elevated privileges
# Changes are saved safely with proper permissions
Safely edits a protected file using the '-e' option (or 'sudoedit'). This creates a temporary copy, opens it in your editor, then overwrites the original with proper ownership and permissions. Much safer than 'sudo vim' because the editor itself doesn't run as root.
Best Practice: Always use sudo -e or sudoedit instead of sudo nano/vim for editing files
Example 6

List Sudo Privileges

$ sudo -l
Matching Defaults entries for user on hostname:
    env_reset, mail_badpass, secure_path=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

User user may run the following commands on hostname:
    (ALL : ALL) ALL
    (root) NOPASSWD: /usr/bin/systemctl restart nginx
    (postgres) /usr/bin/psql
Lists all sudo privileges available to the current user using the '-l' option. Shows which commands you can run, as which users, and whether a password is required. Essential for understanding your permissions on a system.
Useful For: Checking permissions before attempting privileged operations
Example 7

Run Command with Specific Group

$ sudo -g wheel touch /shared/file.txt
# File created with root user but wheel group ownership
Executes a command with a specific group ID using the '-g' option. The command runs as root (or specified user) but with the specified group. Useful for managing shared resources where group ownership matters.
Example: Managing files that need specific group permissions in shared directories
Example 8

Preserve Environment Variables

$ sudo -E env | grep HOME
HOME=/home/user
Preserves user environment variables when running sudo using the '-E' option. By default, sudo resets most environment variables for security. Use -E when you need to maintain your current environment (like PATH, HOME, etc.) in the elevated command.
Security Note: Only use -E when necessary, as it can introduce security risks
Example 9

Run Command in Background

$ sudo -b /usr/local/bin/long-running-process
[sudo] password for user: 
# Command runs in background, prompt returns immediately
Runs a command in the background using the '-b' option. Sudo returns immediately after spawning the process. Useful for starting services or long-running processes that don't need interactive input. The process continues even if you log out.
Use Case: Starting daemons or background maintenance tasks
Example 10

Validate and Update Sudo Timestamp

$ sudo -v
[sudo] password for user: 
# Timestamp updated, next sudo won't ask for password
Validates credentials and updates the sudo timestamp using the '-v' option without running any command. This extends your sudo session so subsequent sudo commands won't require a password (typically for 15 minutes). Useful in scripts that need multiple sudo commands.
Scripts: Run 'sudo -v' at the start of scripts to authenticate once for all subsequent sudo commands
Bonus 1

Kill Sudo Timestamp

$ sudo -k
# Timestamp invalidated, next sudo will require password
Immediately invalidates the sudo timestamp using the '-k' option. Forces the next sudo command to prompt for a password. Good security practice when leaving your terminal or after completing privileged operations.
Security Best Practice: Use this before stepping away from your terminal
Bonus 2

Understanding /etc/sudoers File

$ sudo visudo
# Edit /etc/sudoers safely with syntax checking

# User privilege specification
root    ALL=(ALL:ALL) ALL

# Allow members of group sudo to execute any command
%sudo   ALL=(ALL:ALL) ALL

# Allow user to run specific commands without password
username ALL=(ALL) NOPASSWD: /usr/bin/systemctl restart nginx

# Allow user to run commands as specific user
username ALL=(postgres) /usr/bin/psql
The sudoers file controls who can use sudo and what they can do. Always edit with 'visudo' command which validates syntax before saving. Format: user host=(runas_user:runas_group) commands. NOPASSWD allows running commands without password prompt.
CRITICAL: Never edit /etc/sudoers directly! Always use visudo to prevent syntax errors that could lock you out
Reference

Common sudo Options Quick Reference

Basic Usage:
  sudo command               Run command as root
  sudo -u user command       Run command as specific user
  sudo -g group command      Run command with specific group
  
Shell Access:
  sudo -i                    Login shell as root (clean environment)
  sudo -s                    Shell as root (preserve environment)
  sudo su - username         Switch to another user completely
  
File Operations:
  sudo -e file               Edit file safely (preferred)
  sudoedit file              Same as sudo -e
  
Information:
  sudo -l                    List your sudo privileges
  sudo -ll                   List privileges in long format
  sudo -U user -l            List another user's privileges
  
Environment:
  sudo -E command            Preserve environment variables
  sudo VAR=value command     Set specific environment variable
  
Session Management:
  sudo -v                    Validate/update timestamp
  sudo -k                    Invalidate timestamp immediately
  sudo -K                    Remove timestamp file completely
  
Other Options:
  sudo -b command            Run command in background
  sudo -n command            Non-interactive (fail if password needed)
  sudo -S                    Read password from stdin
  
Common Combinations:
  sudo -u postgres psql      Run psql as postgres user
  sudo -i -u username        Login shell as specific user
  sudo -H command            Set HOME to target user's home
  
Configuration:
  sudo visudo                Edit sudoers file safely
  sudo visudo -f /etc/sudoers.d/custom    Edit custom sudoers file
A comprehensive reference of sudo options for managing privileged access, running commands as different users, and maintaining system security.