Sudo Command in Linux: Run Commands as Root

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:
sudo --versionIf 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
apt install sudoInstall Sudo on Fedora, RHEL, and Derivatives
dnf install sudoAdding 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:
usermod -aG wheel usernameOn Ubuntu, Debian, and their derivatives, members of the sudo group are granted sudo access:
usermod -aG sudo usernameThe 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:
sudo visudoThen append the following line to allow the user linuxize to run only the mkdir
command:
linuxize ALL=(root) /usr/bin/mkdirWhich 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:
sudo EDITOR=vim visudoIf 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 :
linuxize ALL=(ALL) NOPASSWD: ALLHow to Use sudo
The general syntax for the sudo command is:
sudo [OPTION]... COMMANDThe 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:
sudo commandWhere 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:
sudo ls /root[sudo] password for linuxize:
. .. .bashrc .cache .config .local .profileOpen 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:
sudo -iThe -s option starts an interactive shell as root without running a login shell, keeping more of your current environment:
sudo -sYou 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:
sudo -lMatching Defaults entries for linuxize on server:
env_reset, mail_badpass, secure_path=...
User linuxize may run the following commands on server:
(ALL : ALL) ALLTo list privileges for a specific user, pass the -U flag followed by the username:
sudo -l -U usernamePassword 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:
sudo visudoAdd the following line, replacing 10 with the desired timeout in minutes:
Defaults timestamp_timeout=10To set the timeout only for a specific user, use:
Defaults:user_name timestamp_timeout=10Refresh the sudo Timestamp
The -v option renews the cached credentials without running a command, authenticating you first if the cache has already expired:
sudo -vCalling 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:
sudo -N -n -vThe 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:
sudo -kThis 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:
sudo -KRun 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:
sudo -u richard whoamiThe command prints the name of the user running it:
richardCommon 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 lettingsudoreset them. This works when your sudoers rule grantsALL, which is the case for members of thesudoorwheelgroup, and the policy rejects it for narrower rules.-n- Never prompt. When the command needs a password,sudoprints 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- SetHOMEto the target user’s home directory. Fedora and RHEL already do this for every command through thealways_set_homesetting 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 withCWD=*orruncwd=*; otherwisesudoreturns an error.--- Stop parsingsudooptions. Everything after it goes to the command, which matters when the command takes a flag thatsudowould 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:
sudo echo "test" > /root/file.txtbash: /root/file.txt: Permission deniedThis 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:
sudo sh -c 'echo "test" > /root/file.txt'Another option is to pipe the output to the tee command
with sudo:
echo "test" | sudo tee /root/file.txtRunning 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:
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:
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:
sudo -e /etc/hostssudo 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:
SUDO_EDITOR=nano sudo -e /etc/hostsBy 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
| Option | Description |
|---|---|
sudo command | Run a command as root |
sudo -u user command | Run a command as a specific user |
sudo -i | Open a root login shell |
sudo -s | Open a root shell (non-login) |
sudo -l | List sudo privileges for the current user |
sudo -l -U user | List sudo privileges for another user |
sudo -v | Refresh cached credentials without running a command |
sudo -k | Invalidate cached credentials for the current terminal |
sudo -K | Remove cached credentials for every terminal |
sudo -n command | Fail with an error instead of prompting for a password |
sudo -E command | Preserve your current environment variables |
sudo -b command | Run the command in the background |
sudo -H command | Set HOME to the target user’s home directory |
sudo -D dir command | Run in a specific directory when sudoers permits -D |
sudo sh -c '...' | Run a full command line, pipes and redirects included, as root |
sudo -e file | Edit a file as root using your default editor |
sudo visudo | Edit 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.
Tags
Linuxize Weekly Newsletter
A quick weekly roundup of new tutorials, news, and tips.
About the authors

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