sudo Command in Linux: Syntax, Options & Practical Examples

Deepak Prasad
Tested on Ubuntu 25.04 (Plucky Puffin)
Package sudo 1.9.16p2
Applies to Ubuntu, Debian, RHEL, Fedora
Privilege sudo or root
Man page sudo(8)
Scope sudo lets permitted users run commands as root or another account using rules in /etc/sudoers and /etc/sudoers.d/. It logs actions, caches credentials for a timeout, and supports non-interactive and environment-control.
Related guides Linux wheel group
How to create user in Linux
adduser
usermod
Linux commands

sudo — quick reference

Command execution

Run a single command with elevated or alternate identity — the everyday pattern for package installs, service control, and file edits owned by root.

When to use Command
Run a command as root (default target user) sudo whoami
Run as a named user instead of root sudo -u nobody id
Run as a numeric UID (prefix with #) sudo -u '#65534' id
Run with the target user's primary group sudo -g nogroup id
Run in the background and return a shell prompt sudo -b sleep 1
Fail instead of prompting for a password (scripts, CI) sudo -n true
Stop sudo from parsing further options (pass flags to the command) sudo -- whoami

Shell sessions

Open an interactive root shell when you need several admin commands in a row — prefer -i for a full login environment or -s to keep more of your current session.

When to use Command
Start a login shell as root (root environment and HOME) sudo -i whoami
Start a shell as root but keep more of your current environment sudo -s whoami

Environment

Control whether sudo resets or keeps environment variables — important when scripts depend on PATH, HOME, or custom exports.

When to use Command
Preserve the caller's environment (when sudoers allows) sudo -E bash -c 'echo $MY_VAR'
Preserve only named variables sudo --preserve-env=MY_VAR bash -c 'echo $MY_VAR'
Set HOME to the target user's home directory sudo -H bash -c 'echo $HOME'
Set one variable for a single command sudo MY_VAR=value bash -c 'echo $MY_VAR'
Keep the caller's group vector instead of the target's sudo -P id

Credentials and prompts

Refresh, invalidate, or supply the cached password ticket — useful before long admin sessions or when locking a shared terminal.

When to use Command
Refresh cached credentials without running a command sudo -v
Invalidate the timestamp (next sudo asks for a password) sudo -k
Remove the timestamp file completely sudo -K
Read the password from standard input echo '' | sudo -S -n true
Use a helper program for password prompting SUDO_ASKPASS=/bin/false sudo -A true
Ring the terminal bell when prompting sudo -B -n true
Use a custom password prompt string sudo -p 'Password: ' -n true

List privileges

Inspect what sudo allows before you run a risky command or audit another account.

When to use Command
List commands the current user may run with sudo sudo -l
Verbose privilege list (run -l twice) sudo -ll
List privileges for another user (needs permission) sudo -l -U nobody

Edit files

Edit a file as another user — sudo sets a safe editor and temporary file handling.

When to use Command
Edit a file as root (opens $EDITOR) sudo -e /path/to/file
Edit sudoers safely (always prefer this over raw vi /etc/sudoers) sudo visudo

Runtime options

Fine-grained control over file descriptors, working directory, chroot, and timeouts before the command runs.

When to use Command
Close file descriptors from N upward before running sudo -C 3 whoami
Change working directory before running the command sudo -D /tmp whoami
Long form of chdir sudo --chdir=/tmp whoami
Change root directory (chroot) before running sudo -R /var whoami
Long form of chroot sudo --chroot=/var whoami
Terminate the command after a timeout (seconds) sudo -T 30 sleep 60
Long form of command-timeout sudo --command-timeout=30 sleep 60

SELinux context

Set role and type when sudoers and the host policy allow SELinux-aware execution.

When to use Command
Create SELinux security context with a named role sudo -r sysadm_r whoami
Long form of role sudo --role=sysadm_r whoami
Create SELinux security context with a named type sudo -t sysadm_t whoami
Long form of type sudo --type=sysadm_t whoami

Remote host (list mode)

Inspect privileges as if commands ran on another host — only applies with sudo -l.

When to use Command
List privileges for a remote host (when plugin supports it) sudo -l -h host
Long form of host sudo --host=host -l

Help and version

When to use Command
Show built-in usage text sudo --help
Show installed sudo version sudo -V

sudo — command syntax

Synopsis from sudo --help on Ubuntu 25.04 (sudo 1.9.16p2):

text
sudo -h | -K | -k | -V
sudo -v [-ABkNnS] [-g group] [-h host] [-p prompt] [-u user]
sudo -l [-ABkNnS] [-g group] [-h host] [-p prompt] [-U user]
        [-u user] [command [arg ...]]
sudo [-ABbEHkNnPS] [-r role] [-t type] [-C num] [-D directory]
        [-g group] [-h host] [-p prompt] [-R directory] [-T timeout]
        [-u user] [VAR=value] [-i | -s] [command [arg ...]]
sudo -e [-ABkNnS] [-r role] [-t type] [-C num] [-D directory]
        [-g group] [-h host] [-p prompt] [-R directory] [-T timeout]
        [-u user] file ...

Rules live in /etc/sudoers and drop-ins under /etc/sudoers.d/. Edit them only with visudo so a syntax error cannot lock you out of sudo.


sudo — command examples

Essential List what sudo allows — before running admin commands

Before installing packages or editing system files, check what your account may run. sudo -l reads /etc/sudoers and shows matching rules for your user.

Run the command:

bash
sudo -l

Sample output (your host will list different commands):

text
Matching Defaults entries for root on server1:
    env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin, use_pty

User root may run the following commands on server1:
    (ALL : ALL) ALL

Add a second -l for the long format when you need RunAsUsers, RunAsGroups, and per-rule command paths:

bash
sudo -ll

Sample output (truncated):

text
User root may run the following commands on server1:

Sudoers entry: /etc/sudoers
    RunAsUsers: ALL
    RunAsGroups: ALL
    Commands:
	ALL

If the list is empty or says not allowed, your user is not in the sudo group and has no sudoers entry — see Install sudo on Debian or add the account to the right group before retrying.

Essential Run as another user — test permissions without logging in

Use -u when a daemon or service account owns files and you need to confirm access as that identity — common for web roots (www-data) or the unprivileged nobody account.

Run the command:

bash
sudo -u nobody id

Sample output:

output
uid=65534(nobody) gid=65534(nogroup) groups=65534(nogroup)

For a numeric UID, prefix the number with # so sudo treats it as an ID, not a username:

bash
sudo -u '#65534' id

Sample output:

output
uid=65534(nobody) gid=65534(nogroup) groups=65534(nogroup)

Plain sudo -u 65534 fails on Ubuntu because 65534 is parsed as a username, not a UID.

Common Non-interactive mode — scripts and automation

In cron jobs, CI pipelines, or Ansible plays, use -n so sudo exits immediately if a password would be required instead of hanging on a prompt.

Run the command:

bash
sudo -n true

Sample output (success — no lines, exit code 0):

After you invalidate the cache, the same command fails:

bash
sudo -k
sudo -n true

Sample output:

output
sudo: a password is required

Pair -n with a targeted sudoers NOPASSWD rule for specific command paths — never grant passwordless ALL on production hosts without a strong reason.

Common Login shell vs subshell — sudo -i and sudo -s

When you need an interactive admin session, -i simulates a root login (root HOME and login environment). -s starts a root shell but keeps more of your current session variables.

Compare HOME and USER:

bash
sudo -i bash -c 'echo HOME=$HOME USER=$USER'

Sample output:

output
HOME=/root USER=root
bash
sudo -s bash -c 'echo HOME=$HOME USER=$USER'

Sample output:

output
HOME=/root USER=root

For a non-root target user, -i loads that user's login profile; -s is lighter. Prefer sudo command over long root shells when you only need one or two elevated commands.

Common Preserve environment variables — -E and --preserve-env

By default, sudo applies env_reset and clears most variables for safety. When a script needs a specific export, use -E (if sudoers allows SETENV) or --preserve-env=VAR for a narrow list.

Export a test variable:

bash
export MY_VAR=test123
sudo -E bash -c 'echo MY_VAR=$MY_VAR'

Sample output:

output
MY_VAR=test123

Preserve only one variable:

bash
sudo --preserve-env=MY_VAR bash -c 'echo MY_VAR=$MY_VAR'

Sample output:

output
MY_VAR=test123

If the value prints empty, your sudoers Defaults may not allow preserving that variable — check sudo -l for SETENV tags or adjust a drop-in under /etc/sudoers.d/ with visudo.

Common Credential cache — validate, reset, and remove

sudo caches your password for a timeout (often 15 minutes on Ubuntu). Use -v to extend the ticket before a long maintenance window; use -k or -K when you leave a shared console.

Refresh the timestamp without running a command:

bash
sudo -v

Invalidate the cache (next sudo prompts again):

bash
sudo -k
sudo -n whoami

Sample output after -k when a password is required:

text
sudo: a password is required

Remove the timestamp file entirely:

bash
sudo -K

Use -K on logout from jump hosts so the next operator is not accidentally running as a cached sudo session.

Common Set HOME for the target user — sudo -H

Some programs write config or cache files under $HOME. -H points HOME at the target user's home directory (usually /root when you omit -u).

Run the command:

bash
sudo -H bash -c 'echo HOME=$HOME'

Sample output:

output
HOME=/root

Use -H when running pip install --user, editors, or build tools as root so they do not litter files in your personal home directory.

Advanced Background execution and safe file edit

-b runs the command in the background and returns your shell immediately — useful for long-running admin tasks you do not want tied to the terminal.

Run the command:

bash
sudo -b sleep 0.1

Sample output (returns immediately, exit code 0):

For configuration files, sudo -e FILE opens $EDITOR with a temp-file workflow. Prefer visudo for sudoers:

bash
EDITOR=true sudo -e /tmp/example.txt

Sample output when the file is unchanged:

text
sudo: /tmp/example.txt unchanged

Never edit /etc/sudoers with a plain text editor — always sudo visudo or sudo visudo -f /etc/sudoers.d/name.

Advanced Run as a group and pass flags through — -g and --

-g runs the command with the given group as the primary GID. -- tells sudo to stop parsing options so the command can use flags that look like sudo flags.

Run with a specific group:

bash
sudo -g nogroup id

Sample output:

output
uid=0(root) gid=65534(nogroup) groups=65534(nogroup),0(root)

Pass arguments to the command after --:

bash
sudo -- whoami

Sample output:

output
root

Use -- when the command itself starts with - or when you need to be explicit about where sudo's options end.


sudo — when to use / when not

Choose sudo when your account is already authorized in sudoers and you need audited, per-command elevation. Use another tool when you need a full user switch without sudo policy or when sudo is not installed.

Use sudo when Use something else when
  • You are an approved user on a system with /etc/sudoers rules and need to run specific commands as root or another account
  • You want commands logged (syslog/authpriv on Ubuntu) with your login name attached
  • You need non-interactive elevation in scripts with -n and targeted NOPASSWD rules
  • You must edit a file as root using sudo -e or run one-off admin commands without sharing the root password
  • You are on Ubuntu/Debian and your user is in the sudo group — see Install sudo on Debian
  • You need a full interactive login as another user with their password → su
  • sudo is not installed and you have the root password → su - or install the sudo package first
  • You only need to read process or system stats without privilege → ps, top
  • The account is not in sudoers and you cannot change policy → ask an admin to add a drop-in under /etc/sudoers.d/
  • You want passwordless root for every command on a shared server → fix sudoers scope instead of handing out the root password

sudo vs su

Both elevate privilege, but sudo is policy-driven and auditable; su switches identity with the target user's password.

sudo su
Authentication Your password (or NOPASSWD rule) Target user's password (root password for su)
Policy /etc/sudoers, per-command rules None — full shell as target user
Logging Typically logged via syslog Less granular by default
Best for Daily admin on sudo-enabled systems Rescue shells, distros without sudo, becoming another user entirely
Non-interactive -n for scripts su -c 'command'

See the su command when sudo is unavailable or you need a full login as another account.


sudo — interview corner

What is the sudo command in Linux?

sudo (superuser do) runs a single command as root or another user according to rules in /etc/sudoers and files under /etc/sudoers.d/. Your own password (not the root password) usually unlocks it, and actions are logged.

Typical flow:

bash
sudo apt update

Behind the scenes, sudo checks whether your username matches a User_Alias or group like %sudo, whether the command is allowed, and whether your credential cache is still valid.

A strong answer is:

"sudo executes commands as root or another user based on sudoers policy. It prompts for my password, logs the action, and avoids sharing the root password — I use sudo -l to see what I'm allowed to run."

What is the difference between sudo -i and sudo -s?

Both start a shell with elevated privileges, but they differ in how much of a login environment they build.

sudo -i sudo -s
Shell type Login shell Non-login shell
Environment Target user's login profile (/root/.profile, etc.) Keeps more of your current environment
Typical HOME Target user's home (/root) Often target home, but less profile setup
Use case Extended admin session Quick root shell for a few commands

For one command, skip both and run sudo command.

A strong answer is:

"sudo -i is a login shell as the target user with a full root environment; sudo -s is a lighter root shell. For routine work I prefer sudo command instead of staying in a root shell."

How do you list sudo privileges for a user?

Use list mode:

bash
sudo -l

Verbose format (sudo runs -l twice internally):

bash
sudo -ll

To inspect another user (when policy allows):

bash
sudo -l -U username

Sample line you might see on Ubuntu:

text
(ALL : ALL) ALL

A strong answer is:

"I run sudo -l to see allowed commands for my account, sudo -ll for the long format, and sudo -l -U user when auditing someone else if I'm permitted."

What does sudo -n do?

-n is non-interactive mode. sudo never prompts for a password — it succeeds only if credentials are already cached or a NOPASSWD rule covers the command. Otherwise it exits with an error.

bash
sudo -n true

In automation, combine -n with narrow sudoers rules instead of embedding passwords in scripts.

A strong answer is:

"sudo -n fails fast if a password would be needed — I use it in scripts and cron with NOPASSWD rules for specific command paths, not for blanket passwordless root."

How do you edit sudoers safely?

Never edit /etc/sudoers with a normal editor unless you also validate syntax. Use visudo, which locks the file and runs visudo -c before saving:

bash
sudo visudo

For modular rules:

bash
sudo visudo -f /etc/sudoers.d/myapp

Files in /etc/sudoers.d/ should be mode 0440. A syntax error in sudoers can lock every user out of sudo.

A strong answer is:

"I always use visudo or visudo -f for drop-ins under /etc/sudoers.d/, keep files 0440, and test with sudo -l after changes — a bad line can break sudo for everyone."

Why does sudo say 'user is not in the sudoers file'?

The account has no matching rule in sudoers and is not in a privileged group (on Ubuntu, group sudo). Common fixes:

  1. As root, add the user to sudo: usermod -aG sudo username
  2. Or add a drop-in with visudo -f /etc/sudoers.d/username
  3. Log out and back in so group membership refreshes

Verify:

bash
groups username
sudo -l

A strong answer is:

"That error means sudoers has no rule for the user — on Ubuntu I add them to group sudo with usermod -aG sudo, re-login, and confirm with sudo -l. I never hand-edit /etc/sudoers without visudo."


Troubleshooting

Symptom Likely cause Fix
sudo: a password is required with -n Cache expired or no NOPASSWD rule Run sudo -v interactively or add a narrow NOPASSWD entry
sudo: unknown user NNN with -u NNN Numeric UID passed without # Use sudo -u '#65534' command
not permitted to use the -D option sudoers Defaults restrict chdir Remove -D or ask admin to allow it in sudoers
not allowed set a command timeout -T disabled in sudoers Drop -T or request a policy change
sudo: command not found Package not installed sudo apt install sudo (as root) or use su -
Environment variable empty with -E env_reset / no SETENV Use --preserve-env=VAR if allowed, or set vars in the command
Edited /etc/sudoers and sudo broke Syntax error Boot to recovery, fix with visudo, or restore from backup

References

  • visudo(8) man page
Rohan Timalsina

is a technical writer and Linux enthusiast who writes practical guides on Linux commands and system administration. He focuses on simplifying complex topics through clear explanations.

  • Linux
  • HTML5
  • JavaScript
  • Web Design
  • Front-end Web Development