Skip to main content

Linux command: sudo

19 July 2026

Type one wrong command as an ordinary user and Linux stops you with Permission denied. Put the four letters sudo in front of it and, after your own password, the same command runs with the full power of the system. That small word is the front door to root on almost every Linux server. It looks trivial, but behind it sits a careful policy engine, a setuid trick, and a rule file that decides exactly who may do what.

1. The Basics

The job of sudo is to run a single command as another user, normally the superuser root. You stay logged in as yourself, you type your own password, and Linux briefly lends you the extra rights for that one command. When the command finishes, you are back to being an ordinary user.

This is the modern answer to a very old question: how do you let a normal user do a few administrative jobs, such as installing software or restarting a service, without handing them the keys to everything? The old way was to log in as root and stay there, which is dangerous. sudo replaces that with a controlled, logged, per-command grant of power.

Without sudoWith sudo
You act as yourself, limited to your own files One command runs with root's rights
Editing /etc/hosts fails with Permission denied sudo lets that one edit through
No record of who tried what Every use is written to the system log

One short word that lends you the power of root for exactly one command. Behind it sit a setuid binary, a policy file that names who may do what, and a timer that remembers you for a few minutes.

This article starts with the simplest use and builds up step by step to the sudoers policy file, the group that grants access, safe file editing with sudoedit, and the setuid mechanism that makes the whole thing work. By the end, that everyday word will make complete sense.

The right mental model: sudo is not a way to "become root and stay there". It is a doorway you step through for a single command, while a rule file watches who is allowed through and a log writes down that you did.

1.1 The Very First Time

The first time you use sudo, it asks for a password and prints a short lecture:

$ sudo apt update
We trust you have received the usual lecture from the local System
Administrator. It usually boils down to these three things:

    #1) Respect the privacy of others.
    #2) Think before you type.
    #3) With great power comes great responsibility.

[sudo] password for peter:

Notice one thing that surprises newcomers: it asks for your password, not root's. That is the whole point. You never need to know the root password; you only need permission, granted in advance, to act as root.

Back to top

2. Where the Name Comes From

The name sudo is usually read as superuser do: "do this as the superuser".

sudo  =  SuperUser DO

There is a second, more precise reading. Because sudo can run a command as any user, not only root, it is also explained as substitute user do: "do this as a substitute user". Both readings are common, and the manual page itself simply says "execute a command as another user", which covers both.

The related older command su follows the same logic. It is short for substitute user (often mis-remembered as "superuser"), and it switches your whole session to another user. sudo was designed as a safer, finer-grained relative of su, which is why the names rhyme.

Back to top

3. A Short History

sudo is older than Linux itself. It was written around 1980 by Bob Coggeshall and Cliff Spencer at the Department of Computer Science at the State University of New York at Buffalo, so that a few users could run administrative commands on a shared VAX without sharing the root password. The idea proved so useful that it spread across the Unix world and was rewritten and extended many times.

EraMilestone
~1980 First sudo written at SUNY/Buffalo to share limited root access
1994 Todd C. Miller takes over maintenance; sudo becomes the version we use today
2000s Most Linux distributions adopt sudo as the standard way to gain root
Today Modern sudo (1.9.x) adds plugins, JSON logging, and central policy control

A turning point for ordinary users was Ubuntu. From its first release in 2004, Ubuntu shipped with the root account locked and told users to do everything through sudo instead. That choice, later copied by many desktop distributions, is why a huge number of Linux users have never once typed the root password. This article describes the widely used Sudo project version maintained by Todd Miller, verified against version 1.9.15.

Back to top

4. Simple Use Cases

4.1 Running One Command as Root

This is the everyday case. You put sudo in front of a command that needs administrative rights:

$ apt install htop
E: Could not open lock file /var/lib/dpkg/lock-frontend - Permission denied

$ sudo apt install htop
[sudo] password for peter:
Reading package lists... Done

Only the command right after sudo runs with extra rights. Everything before and after it is still plain you.

4.2 Fixing a Forgotten sudo: the Magic sudo !!

You run a command, it fails for lack of permission, and you realise you forgot sudo. Instead of typing the whole line again, repeat the previous command with !! (the shell's "last command" shortcut):

$ systemctl restart nginx
Failed to restart nginx.service: Access denied

$ sudo !!
sudo systemctl restart nginx
[sudo] password for peter:

The shell expands !! into the previous command, so sudo !! becomes "run that same command again, but as root". It is one of the most-loved shortcuts in daily Linux work.

4.3 Running as a Different User

By default sudo runs the command as root, but the -u flag (short for user) lets you name any target user. This is common when a service runs under its own account:

$ sudo -u postgres psql       # run psql as the postgres user
$ sudo -u www-data whoami     # confirm the identity
www-data

So "sudo" does not always mean "root". It means "run as the user policy allows", and root is only the default.

4.4 Checking What You May Do: -l

Before you go looking for a password, you can ask sudo what it will let you do. The -l flag (short for list) prints your privileges:

$ sudo -l
User peter may run the following commands on server:
    (ALL : ALL) ALL

The line (ALL : ALL) ALL means "as any user, as any group, run any command". A more limited account might instead show a single service it is allowed to restart, and nothing else.

Back to top

5. Moderate Use Cases

5.1 The Timestamp: Why It Stops Asking

After you type your password once, sudo stops asking for a short while. This is the timestamp: once you authenticate, sudo records the time and, by default, trusts you for 15 minutes in that terminal before asking again.

The record lives in a small file under /run/sudo/ts/, owned by root and readable only through sudo itself. Two flags let you control it directly:

$ sudo -v      # validate: refresh the timer without running a command
$ sudo -k      # kill: forget the timestamp, so the next sudo asks again

The -v flag (short for validate) is handy at the start of a long script, so the password prompt does not appear in the middle of the work. The -k flag (short for kill or reset) is a good habit when you step away from a shared machine.

5.2 The sudo Group: How Permission Is Granted

Who is allowed to use sudo in the first place? On most systems, membership of a single group decides it. On Debian and Ubuntu that group is called sudo; on Red Hat, Fedora, and their relatives it is called wheel. Add a user to that group and they gain sudo rights:

$ sudo usermod -aG sudo alice     # Debian / Ubuntu
$ sudo usermod -aG wheel alice     # Red Hat / Fedora

You can see your own groups with the groups command:

$ groups
peter adm cdrom sudo dip plugdev

The word sudo in that list is what lets this user run administrative commands. Group changes take effect at the next login, so a new member must log out and back in.

5.3 sudo Versus su

Both commands give you another user's rights, but they work in opposite ways, and knowing the difference marks the step from beginner to confident user.

sudo commandsu
Whose password? Your own The target user's (often root's)
Scope One command, then back to you A whole new shell as that user
Control Fine-grained, per command, per user All or nothing
Record Each command is logged Only the switch is logged

Because sudo asks for your own password and can be limited to exactly the commands you need, it is safer than sharing the root password with everyone. That is why modern systems prefer it.

Back to top

6. Advanced Use Cases

6.1 The sudoers File and visudo

All of sudo's decisions come from one policy file: /etc/sudoers. It lists who may run which commands, as whom, and whether a password is required. You never edit it with a plain text editor. You use visudo, which locks the file, opens your editor, and, crucially, checks the syntax before saving:

$ sudo visudo

That syntax check is not a nicety. A single typo in /etc/sudoers can lock every user out of sudo at once, and then you have no easy way back in. visudo refuses to save a broken file, which has rescued countless administrators.

A few lines from a typical sudoers file explain the format:

root    ALL=(ALL:ALL) ALL
%sudo   ALL=(ALL:ALL) ALL

Read the second line left to right: the %sudo means "members of the group named sudo", the first ALL is "on any host", (ALL:ALL) is "may run as any user and any group", and the last ALL is "any command". The leading % is what marks a group rather than a single user.

6.2 Drop-in Files: /etc/sudoers.d/

Rather than editing the main file, modern practice is to add a small file in the /etc/sudoers.d/ directory. Each file there is read as part of the policy, which keeps custom rules separate and easy to remove. Always create them with visudo -f so the syntax is still checked:

$ sudo visudo -f /etc/sudoers.d/deploy

6.3 Passwordless Commands: NOPASSWD

Sometimes a script or an automation account must run one specific command as root without stopping for a password. The NOPASSWD tag allows exactly that, and only that:

deploy  ALL=(root) NOPASSWD: /usr/bin/systemctl restart myapp

This lets the deploy user restart one service, with no password, and do nothing else as root. That is the right way to use NOPASSWD: narrow it to a single, exact command. Granting NOPASSWD: ALL hands out full passwordless root and throws the safety away.

6.4 A Login Shell or a Plain Shell: -i and -s

When you really do need an interactive root shell, two flags give it to you:

$ sudo -i      # a full login shell as root (loads root's environment)
$ sudo -s      # a shell as root, but keep your own environment

The -i flag (short for login) behaves as if root had just logged in: it moves to root's home directory and reads root's startup files. The -s flag (short for shell) starts a root shell but stays in your current directory with much of your own environment. Use these sparingly; the whole spirit of sudo is one command at a time.

6.5 Editing Files Safely: sudoedit

A very common task is editing a root-owned config file. The tempting way is sudo vim /etc/nginx/nginx.conf, but that runs your entire editor as root, with all its plugins and shell escapes, which is more power than the job needs. The safer tool is sudoedit, also reachable as sudo -e:

$ sudoedit /etc/nginx/nginx.conf
$ sudo -e /etc/nginx/nginx.conf     # exactly the same thing

What happens under the hood is clever. sudoedit copies the file to a temporary place, runs your editor as you (not as root), and only writes the result back as root when you save. Your editor never runs with root's power, which closes a whole class of security holes. It also respects your own $EDITOR setting.

6.6 The Environment: env_reset and secure_path

For safety, sudo does not simply carry your environment into the root command. By default (the env_reset option) it starts from a clean, minimal environment and uses a fixed, trusted secure_path for finding programs. This stops a user from pointing PATH at a malicious fake command and having root run it.

Two consequences catch people out. First, a variable you exported may not be visible inside sudo; pass it through with -E (short for preserve-env) or name it explicitly:

$ sudo -E ./deploy.sh                 # keep the whole environment
$ sudo --preserve-env=HTTP_PROXY cmd  # keep just one variable

Second, a program in an unusual directory may be "not found" under sudo even though your shell finds it, because secure_path is deliberately short. Give the full path in that case.

Back to top

7. Something Most Users Do Not Know

7.1 sudo Works Because It Is setuid root

How can a program started by an ordinary user suddenly act as root? The answer is a single permission bit on the sudo binary itself. Look closely:

$ ls -l /usr/bin/sudo
-rwsr-xr-x 1 root root 277936 Mar  2 13:56 /usr/bin/sudo

Notice the s where the owner's execute bit would normally be, and that the owner is root. That s is the setuid bit. It means: whoever runs this program, the program runs with the identity of its owner, which here is root. So the moment you launch sudo, it is already running as root, and it then decides, by reading /etc/sudoers, whether you are allowed to ask for what you asked.

sudo is not magic and it is not part of the kernel. It is an ordinary program wearing a setuid bit, trusted to run as root and honest enough to check the rule file before doing what you told it to.

This is also why sudo itself must be owned by root and must never be world-writable: if an attacker could change the sudo binary, the setuid bit would run their code as root. The same mechanism powers su and passwd.

7.2 Real, Effective, and Saved User IDs

The setuid bit works because every Linux process carries not one identity but three user IDs at once:

User IDWhat it is
Real UID Who actually started the process (you)
Effective UID Whose permissions the kernel checks on every access
Saved UID A parked copy, so a program can drop a privilege and pick it up again later

The effective UID is the one that counts: it decides what the process may read, write, and run. When you launch sudo, the setuid bit sets its effective UID to 0 (root), while your own ID stays as the real UID. That is the split-second state in which sudo reads the policy and authenticates you.

When sudo then runs your command, it does not stop at a half-changed identity. It sets all three IDs to the target user, so the command becomes fully that user, root by default, with no leftover trace of you in its credentials. This is a real difference from a program that merely borrows root for an instant: your command runs as a first-class root process for its whole life, then exits, and you are yourself again.

7.3 How sudo Checks Your Password: PAM

When sudo asks for your password, it does not verify the password itself. It hands that job to PAM (Pluggable Authentication Modules), the standard Linux framework that every login-style tool uses to decide "is this really you?". The rules for sudo live in a small file:

$ cat /etc/pam.d/sudo
@include common-auth
@include common-account
@include common-session-noninteractive

Because PAM is pluggable, an administrator can change what "authenticate" means without touching sudo at all. Requiring a one-time code from an authenticator app, a fingerprint, or a check against a central LDAP directory is a matter of editing the PAM configuration, not the sudo binary. This is also why sudo stays in step with the rest of the system's login behaviour: they all pass through the same PAM stack.

7.4 Every Use Is Logged

Unlike logging in as root, which leaves little trace of what was done, sudo records each command. On a systemd machine you can read the trail with journalctl:

$ sudo journalctl -e | grep sudo
... sudo: peter : TTY=pts/0 ; PWD=/home/peter ; USER=root ;
     COMMAND=/usr/bin/systemctl restart nginx

The same records also land in a plain text log file, which is handy on servers without journalctl or when you want to grep history directly. The location depends on the distribution: /var/log/auth.log on Debian and Ubuntu, and /var/log/secure on Red Hat and Fedora.

This log is one of sudo's quiet strengths. On a shared server it answers the question "who restarted the database at 3am?" long after the moment has passed. Modern sudo can even record the full terminal session for later replay.

7.5 sudo Is Trusted Code, So Keep It Updated

Because sudo runs as root by design, a bug in sudo can be unusually serious: it may let an ordinary user become root without permission. This is not theoretical. In 2021 a flaw nicknamed Baron Samedit (CVE-2021-3156) let any local user gain root through a parsing error that had been present for years. It was fixed quickly, but the lesson is lasting: a program this powerful must be kept up to date. When your system offers a sudo security update, it is not one to postpone.

Back to top

8. Best Practices

  • Use sudo, not a root login. Running individual commands with sudo keeps a log, uses your own password, and lets you drop straight back to a safe, ordinary account.
  • Always edit the policy with visudo. Never open /etc/sudoers directly. The syntax check that visudo performs is what stands between you and being locked out.
  • Prefer drop-in files. Put custom rules in /etc/sudoers.d/ (created with visudo -f) so they are easy to review and remove without touching the main file.
  • Grant the least you can. If an account only needs to restart one service, write exactly that command in the rule. Avoid handing out (ALL) ALL when a single line will do.
  • Edit files with sudoedit. Reach for sudoedit file instead of sudo vim file so your editor never runs with root's power.
  • Be very careful with NOPASSWD. It is useful for one narrow automated command, but NOPASSWD: ALL gives away full passwordless root.
  • Read the manual when unsure. The behaviour is all documented, and typing man sudo or man sudoers is the mark of a careful administrator.
$ man sudo         # the sudo command itself
$ man sudoers      # the policy file format, with many examples
$ sudo --help      # a quick summary of the options
Back to top

9. Common Mistakes

9.1 Myth versus Reality

MythReality
"sudo asks for the root password." It asks for your own password. You may never learn the root password at all.
"sudo always means become root." It runs as any user the policy allows. sudo -u postgres runs as postgres, not root.
"sudo command1 | command2 runs both as root." Only command1 is elevated. The part after the pipe runs as you. Wrap the pipeline in sudo sh -c '...' if you need it all as root.
"sudo cmd > /root/file writes the file as root." The shell opens the redirect as you, before sudo runs, so it fails. Use sudo tee instead.
"Editing with sudo vim is fine." It runs your whole editor as root. sudoedit is the safer tool for the same job.

9.2 Other Traps to Avoid

  • The redirection trap. sudo echo text > /etc/file fails with "Permission denied" because your shell, not sudo, creates the file. The fix is echo text | sudo tee /etc/file.
  • Editing /etc/sudoers by hand. One typo can disable sudo for everyone. Always use visudo, which checks the file before saving.
  • Reaching for sudo when the fix is ownership. If your own files keep needing sudo, they probably belong to the wrong user. chown is often the real answer.
  • Blindly pasting curl ... | sudo bash. This runs code you have not read with full root rights. Download and read the script first.
  • Starting graphical programs with sudo. Running sudo gedit or sudo firefox lets a root-owned process write config files into your home directory (for example under ~/.config), which then lock you out of your own settings. Edit files with sudoedit, or use an application's own administrator mode instead.
  • Forgetting the environment resets. A variable or a program on an unusual PATH may vanish under sudo. Use sudo -E or a full path when needed.
  • Leaving a machine with the timestamp warm. On a shared computer, run sudo -k when you walk away so nobody rides your 15-minute grace period.
Back to top

10. Summary

The sudo command is short, but it governs the most important question on a Linux system: who is allowed to act as root, and for exactly what.

  • sudo runs a single command as another user, normally root, after asking for your own password.
  • The name reads as "superuser do" (or "substitute user do", since it can run as any user).
  • It was written around 1980 at SUNY/Buffalo and is now maintained as the Sudo project; Ubuntu made it the standard way to gain root.
  • Put it in front of a command; use sudo !! to repeat the last one as root, and -u to run as a specific user.
  • A timestamp remembers you for 15 minutes; -v refreshes it and -k forgets it.
  • Permission comes from a group, sudo on Debian and Ubuntu, wheel on Red Hat and Fedora.
  • The policy lives in /etc/sudoers and drop-in files under /etc/sudoers.d/, always edited with visudo.
  • Use sudoedit to change root-owned files safely, and -i or -s only when you truly need a root shell.
  • sudo works because its binary is setuid root; that is also why it must be kept owned by root and up to date.
  • Under the hood it sets the process's real, effective, and saved user IDs to the target, and checks your password through PAM.
  • Every use is logged, which is one of its biggest advantages over logging in as root.

This is the quick reference worth keeping:

sudo command             run one command as root
sudo -u user command     run it as another user
sudo !!                  repeat the previous command as root
sudo -l                  list what you are allowed to run
sudo -v                  refresh the 15-minute timestamp
sudo -k                  forget the timestamp now
sudo -i                  a full root login shell
sudoedit /etc/file       edit a root-owned file safely
echo x | sudo tee file   write to a root-owned file
sudo visudo              edit the sudoers policy safely
sudo usermod -aG sudo u  grant a user sudo rights (Debian/Ubuntu)

Getting sudo right is one of the quiet foundations of a secure server: the difference between a machine where every action is scoped and logged, and one where a single shared root password floats around. If you are unsure whether your server's sudo rules grant too much, or you want passwordless automation set up without opening a hole, it pays to have someone review the whole policy properly before a convenient NOPASSWD: ALL becomes tomorrow's incident.

Back to top
Linux command: sudo
Peter Martin
Peter Martin
Joomla Specialist

Peter is a Joomla specialist and a Linux admin for fast, secure and scalable websites.