Sudo Command in Linux: Run Commands as Root

By 

Updated on

12 min read

Linux sudo command running a command as root in a terminal

The sudo command allows you to run programs as another user, by default the root user. You will use it whenever a task requires administrative privileges, such as managing packages, services, users, or system configuration files.

This guide explains how to use the sudo command on Linux, covering common options, sudoers configuration, and real-world examples.

What Is sudo

The name is short for “su do”, and the sudo project describes it as a way to delegate authority: certain users, or groups of users, are allowed to run some or all commands as root or another user. By default, sudo logs successful and unsuccessful attempts to run commands.

That delegation is what separates sudo from shared root access, where actions are not tied to each person’s normal account. With sudo, each person usually authenticates with their own password, the rules in /etc/sudoers decide which commands they are allowed to run, and the log identifies the account that invoked sudo. Those rules can grant full administrative access, or a single command and nothing else.

sudo logs the command it starts, not each command entered inside sudo -i or another privileged shell. Commands inside that shell are logged only when an administrator enables I/O logging.

Installing Sudo

The sudo package is pre-installed on most Linux distributions.

To check whether sudo is installed on your system, run:

Terminal
sudo --version

If sudo is not installed, you will see a sudo: command not found error. To install it, run the following commands as the root user. On systems with an enabled root account, switch to root first with su -; otherwise use another admin account or a root recovery shell.

Install Sudo on Ubuntu, Debian, and Derivatives

Terminal
apt install sudo

Install Sudo on Fedora, RHEL, and Derivatives

Terminal
dnf install sudo

Adding a User to Sudoers

By default, on most Linux distributions, granting sudo access is as simple as adding the user to the sudo group defined in the sudoers file . Members of this group can run any command as root. The name of the group differs between distributions.

On Fedora, RHEL, and their derivatives, the sudo group is named wheel. To add the user to the group , run:

Terminal
usermod -aG wheel username

On Ubuntu, Debian, and their derivatives, members of the sudo group are granted sudo access:

Terminal
usermod -aG sudo username

The root user account in Ubuntu is disabled by default for security reasons, and users are encouraged to perform system administration tasks using sudo. The initial user created by the Ubuntu installer is already a member of the sudo group.

To allow a specific user to run only certain programs as sudo, add the user directly to the sudoers file instead of the group. Open the file with visudo:

Terminal
sudo visudo

Then append the following line to allow the user linuxize to run only the mkdir command:

ini
linuxize  ALL=(root) /usr/bin/mkdir

Which editor visudo opens depends on how the sudo package was built. Current Debian, Ubuntu, and Fedora builds all reach nano first. Before falling back to that default, visudo checks the SUDO_EDITOR, VISUAL, and EDITOR variables, so you can choose a different editor for a single run:

Terminal
sudo EDITOR=vim visudo

If you land in vim without meaning to, see our article on how to save a file and quit the vim editor .

You can also allow users to run sudo commands without entering a password :

ini
linuxize  ALL=(ALL) NOPASSWD: ALL

How to Use sudo

The general syntax for the sudo command is:

Terminal
sudo [OPTION]... COMMAND

The sudo command has many options that control its behavior, but it is most commonly used in its basic form without any options.

To run a command as root, prefix it with sudo:

Terminal
sudo command

Where command is the command you want to run with elevated privileges.

The first time you use sudo in a session, you will be prompted to enter your user password. Once authenticated, sudo reads /etc/sudoers to verify the user has permission, then executes the command as root.

For example, to list the contents of the /root directory:

Terminal
sudo ls /root
output
[sudo] password for linuxize:
.  ..  .bashrc  .cache  .config  .local  .profile

Open a Root Shell

Instead of prefixing every command with sudo, you can open an interactive root shell for an extended session.

The -i option starts a login shell as root, loading root’s environment, home directory, and shell configuration:

Terminal
sudo -i

The -s option starts an interactive shell as root without running a login shell, keeping more of your current environment:

Terminal
sudo -s

You can also reach a root shell through the su command by running sudo su -, though sudo -i gives you the same login shell in a single step.

Use exit or press Ctrl+D to return to your normal user session.

List sudo Privileges

To see what commands the current user is allowed to run with sudo, use the -l option:

Terminal
sudo -l
output
Matching Defaults entries for linuxize on server:
    env_reset, mail_badpass, secure_path=...

User linuxize may run the following commands on server:
    (ALL : ALL) ALL

To list privileges for a specific user, pass the -U flag followed by the username:

Terminal
sudo -l -U username

Password Timeout

After you authenticate successfully, sudo caches your credentials so that the next command does not prompt again. The upstream sudoers policy defaults to five minutes, but distributions can choose a different value when building the package. Current Debian and Ubuntu packages use 15 minutes, while Fedora uses the upstream five-minute default. An administrator can override either value in the sudoers configuration.

The cache is also per terminal. sudo keeps a separate timestamp record for each one, so a password entered in one shell does not carry over to a second shell opened beside it. That behavior comes from the timestamp_type setting, which defaults to tty.

To change the default timeout, open the sudoers file with visudo:

Terminal
sudo visudo

Add the following line, replacing 10 with the desired timeout in minutes:

ini
Defaults  timestamp_timeout=10

To set the timeout only for a specific user, use:

ini
Defaults:user_name  timestamp_timeout=10

Refresh the sudo Timestamp

The -v option renews the cached credentials without running a command, authenticating you first if the cache has already expired:

Terminal
sudo -v

Calling it at the start of a long script or build starts a fresh timeout period, reducing the chance of a password prompt during the next privileged step. A later sudo command will still prompt if that period has expired.

The -N option was added in sudo 1.9.12. On sudo 1.9.12 and newer, you can test whether valid credentials already exist without prompting or extending the cache by combining -v with -N and -n:

Terminal
sudo -N -n -v

The command exits with a status of 0 while the cache is still valid. Once it expires, sudo prints an error and exits non-zero instead of asking for a password, which is what makes the check safe to run unattended.

Invalidate the sudo Timestamp

To manually clear the cached credentials and force sudo to prompt for a password on the next use, run:

Terminal
sudo -k

This is useful when you finish a privileged session and want to require re-authentication immediately.

Because credentials are cached per terminal, -k only clears the record belonging to the terminal you run it in. The uppercase form removes every cached credential for your account, whichever terminal created it:

Terminal
sudo -K

Run a Command as Another User

There is a common misconception that sudo is used only to provide root privileges. You can use sudo to run a command as any user by passing the -u option.

In the following example, we are using sudo to run the whoami command as the user richard:

Terminal
sudo -u richard whoami

The command prints the name of the user running it:

output
richard

Common sudo Options

A handful of options beyond the ones already covered come up often enough in scripts and daily administration to be worth knowing:

  • -E - Preserve your current environment variables instead of letting sudo reset them. This works when your sudoers rule grants ALL, which is the case for members of the sudo or wheel group, and the policy rejects it for narrower rules.
  • -n - Never prompt. When the command needs a password, sudo prints an error and exits rather than waiting for input. Use it in cron jobs and scripts that have no terminal to prompt on.
  • -b - Run the command in the background. Shell job control does not reach the resulting process, so you cannot bring it back to the foreground.
  • -H - Set HOME to the target user’s home directory. Fedora and RHEL already do this for every command through the always_set_home setting in their default sudoers file.
  • -D - Request that the command run in a given directory instead of the current one. The matching sudoers rule must allow this with CWD=* or runcwd=*; otherwise sudo returns an error.
  • -- - Stop parsing sudo options. Everything after it goes to the command, which matters when the command takes a flag that sudo would otherwise claim as its own.

How to Redirect with sudo

If you try to redirect output to a file that your current user does not have write permission for, you will get a “Permission denied” error:

Terminal
sudo echo "test" > /root/file.txt
output
bash: /root/file.txt: Permission denied

This happens because the shell processes the > redirection before invoking sudo, so the redirect runs as your regular user, not root.

One solution is to start a subshell as root using sudo sh -c:

Terminal
sudo sh -c 'echo "test" > /root/file.txt'

Another option is to pipe the output to the tee command with sudo:

Terminal
echo "test" | sudo tee /root/file.txt

Running Pipes and Multiple Commands

The same rule applies to every shell operator, not only >. In sudo cat /etc/shadow | wc -l, only cat runs as root, while the pipe and wc run as your own user. In sudo cd /root, cd is a shell builtin rather than a program on disk, so sudo has nothing to execute:

output
sudo: cd: command not found
sudo: "cd" is a shell built-in command, it cannot be run directly.
sudo: the -s option may be used to run a privileged shell.
sudo: the -D option may be used to run a command in a specific directory.

Wrapping the whole line in sh -c puts all of it under root:

Terminal
sudo sh -c 'cd /root && ls -l | wc -l'

Use single quotes around the string so that your own shell leaves the operators alone and hands them to the root shell intact.

Edit Files as Root with sudoedit

Running sudo vim /etc/hosts opens the file, but it also starts a full editor as root, and any plugin, macro, or shell escape inside that editor runs as root too. The -e option avoids that, and it is also available under the name sudoedit:

Terminal
sudo -e /etc/hosts

sudo makes a temporary copy of the file owned by you, runs the editor as your normal user, and copies the result back to the original location when you exit. The editor itself never holds root privileges. If the file does not exist yet, it is created.

The editor comes from SUDO_EDITOR, VISUAL, or EDITOR, in that order, and falls back to the list configured in the sudoers policy when none of them are set:

Terminal
SUDO_EDITOR=nano sudo -e /etc/hosts

By default, sudoedit refuses symbolic links and files in directories you can write to yourself. The sudoers policy can explicitly allow those cases, but device files are always refused.

Quick Reference

OptionDescription
sudo commandRun a command as root
sudo -u user commandRun a command as a specific user
sudo -iOpen a root login shell
sudo -sOpen a root shell (non-login)
sudo -lList sudo privileges for the current user
sudo -l -U userList sudo privileges for another user
sudo -vRefresh cached credentials without running a command
sudo -kInvalidate cached credentials for the current terminal
sudo -KRemove cached credentials for every terminal
sudo -n commandFail with an error instead of prompting for a password
sudo -E commandPreserve your current environment variables
sudo -b commandRun the command in the background
sudo -H commandSet HOME to the target user’s home directory
sudo -D dir commandRun in a specific directory when sudoers permits -D
sudo sh -c '...'Run a full command line, pipes and redirects included, as root
sudo -e fileEdit a file as root using your default editor
sudo visudoEdit the sudoers file safely

Troubleshooting

username is not in the sudoers file
The user has not been added to the sudoers group. Log in as root and run usermod -aG sudo username (Ubuntu/Debian) or usermod -aG wheel username (RHEL/Fedora), then log out and back in for the group change to take effect.

sudo: unable to resolve host hostname
The system hostname does not match an entry in /etc/hosts. Add an entry for your hostname in /etc/hosts (for example, 127.0.1.1 hostname on Ubuntu and Debian), then try again.

sudo: command not found after using sudo -i or sudo -s
The root shell may use a restricted PATH that does not include your command’s directory. Use the full path to the command (for example, /usr/local/bin/command), or run sudo env PATH="$PATH" command to preserve your current path. When sudo itself is the missing command rather than the program you are calling, see our guide on how to fix “sudo: command not found” .

FAQ

What is the difference between sudo and su?
sudo runs a single command as another user (usually root) and requires your own password. su switches to another user account entirely and requires that user’s password. sudo is preferred for one-off privileged commands; su is used to fully switch user sessions.

How do I re-run the last command with sudo?
Use sudo !!, the !! expands to the last command in your shell history, and sudo runs it with elevated privileges.

How do I run sudo without entering a password?
Add a NOPASSWD rule in the sudoers file: linuxize ALL=(ALL) NOPASSWD: ALL. See our guide on running sudo without a password .

How long does sudo remember my password?
Current Debian and Ubuntu packages default to 15 minutes, while Fedora uses the upstream five-minute default. An administrator can change the timeout with Defaults timestamp_timeout=N, and sudo -v renews the cache without running a command.

Conclusion

The sudo command is an essential tool for Linux system administration. It lets you run commands with elevated privileges while keeping your system secure by avoiding direct root logins. Use sudo -l to inspect your privileges, sudo -i to open a root shell, and sudo -k to clear the credential cache when you are done.

Linuxize Weekly Newsletter

A quick weekly roundup of new tutorials, news, and tips.

About the authors

Dejan Panovski

Dejan Panovski

Dejan Panovski is the founder of Linuxize, an RHCSA-certified Linux system administrator and DevOps engineer based in Skopje, Macedonia. Author of 800+ Linux tutorials with 20+ years of experience turning complex Linux tasks into clear, reliable guides.

View author page