sudo – execute command as another user

sudo runs commands with elevated (root) privileges. It’s the standard way to perform administrative tasks without logging in as root.

Synopsis

sudo [OPTIONS] COMMAND

Common Options

OptionDescription
-u USERRun as specified user (not root)
-iLogin shell as target user
-sRun shell as target user
-lList allowed commands for user
-kInvalidate cached credentials
-vExtend credential timeout
-EPreserve environment variables

Examples

Run command as root

$ sudo apt update
[sudo] password for greys: 
...

Edit system file

$ sudo nano /etc/hosts
$ sudo vim /etc/ssh/sshd_config

Run as different user

$ sudo -u postgres psql
$ sudo -u www-data cat /var/www/.htaccess

Get root shell

$ sudo -i    # Login shell (loads root's profile)
$ sudo -s    # Shell without login

List your sudo permissions

$ sudo -l
User greys may run the following commands:
    (ALL : ALL) ALL

Reset sudo timeout

$ sudo -k    # Forget credentials, will prompt again

Preserve environment

$ sudo -E command    # Keep $HOME, $PATH, etc.

Run command in background

$ sudo nohup long_process &

Common Patterns

Edit protected file (safe way)

$ sudoedit /etc/sudoers    # Uses $EDITOR safely

Run last command with sudo

$ apt update
E: Could not open lock file
$ sudo !!    # Runs: sudo apt update

Chain commands

$ sudo sh -c 'echo "127.0.0.1 test" >> /etc/hosts'

Redirect output as root

# This doesn't work (redirect runs as user):
$ sudo echo "test" > /etc/test.txt    # Permission denied

# This works:
$ echo "test" | sudo tee /etc/test.txt
$ sudo sh -c 'echo "test" > /etc/test.txt'

Sudoers Configuration

Edit with visudo (validates syntax):

$ sudo visudo

Example entries:

# User can run all commands
greys ALL=(ALL:ALL) ALL

# User can run specific commands without password
greys ALL=(ALL) NOPASSWD: /usr/bin/apt, /usr/bin/systemctl

# Group can run commands
%admin ALL=(ALL) ALL

Tips

  • Use visudo: Never edit /etc/sudoers directly
  • Least privilege: Grant only needed commands in sudoers
  • Audit: Sudo logs to /var/log/auth.log or /var/log/secure
  • Timeout: Default 15 minutes before re-prompting
  • NOPASSWD: Use sparingly, security risk

See Also

  • su — Switch user entirely
  • visudo — Safely edit sudoers
  • whoami — Show current user
  • id — Show user and group IDs

Tutorials