DEV Community

Cover image for Sudo vs Root: What's the Difference?
Asep Sayyad
Asep Sayyad

Posted on Originally published at asepsayyad007.Medium

Sudo vs Root: What's the Difference?

The architectural differences between the root account and sudo delegation, how the SUID bit works, why visudo saves production servers, and how to manage privileges safely.

When you first start working with Linux, you run into permission errors constantly.

You try to update your packages, edit a web server config, or mount a hard drive, and the terminal immediately pushes back:

$ apt update
Reading package lists... Done
E: Could not open lock file /var/lib/apt/lists/lock - open (13: Permission denied)
E: Unable to lock directory /var/lib/apt/lists/
Enter fullscreen mode Exit fullscreen mode

Most beginners search for a fix and find a simple tip: just put sudo in front of your command.

$ sudo apt update
[sudo] password for asep:
Hit:1 http://archive.ubuntu.com/ubuntu jammy InRelease
Get:2 http://security.ubuntu.com/ubuntu jammy-security InRelease [110 kB]
...
Fetched 110 kB in 1s (115 kB/s)
Reading package lists... Done
Enter fullscreen mode Exit fullscreen mode

You type your password, the command works, and you move on.

Soon, you start hearing people use "root" and "sudo" interchangeably. Some engineers tell you to log in as root to get things done faster. Others tell you that logging in as root is a dangerous mistake that will get you fired from a sysadmin job.

Are root and sudo just two different names for the same administrative superpower?

The short answer is no. Root is an identity with total power over the entire operating system. Sudo is a tool that temporarily grants specific administrative privileges to regular users under strict rules.

Understanding the difference between the two is one of the most critical steps in mastering Linux administration and securing production infrastructure.

Let's break down how root and sudo work under the hood, how they differ, and why modern systems rely on sudo for everyday operations.


1. What is Root in Linux?

In Linux and Unix-like operating systems, root is the default superuser account.

Every user on a Linux system is identified by a numerical identifier called a User ID (UID). Normal user accounts usually start at UID 1000 on modern distributions like Ubuntu, Debian, Red Hat, and Fedora. System service accounts (like www-data, nginx, or systemd-resolve) get lower UIDs between 1 and 999.

The root user always has UID 0 and GID 0 (Group ID 0).

$ id root
uid=0(root) gid=0(root) groups=0(root)
Enter fullscreen mode Exit fullscreen mode

Total Kernel Authority

In standard Linux Discretionary Access Control (DAC), the operating system checks file permissions (rwx) for three groups: the owner, the group, and everyone else.

If a regular user tries to write to /etc/shadow or read another user's private SSH keys in /home/otheruser/.ssh/id_rsa, the Linux kernel checks the file mode bits, sees that the user does not have permission, and returns an EACCES (Permission denied) error code.

The root user (UID 0) bypasses almost all of these permission checks entirely.

The kernel treats UID 0 as an all-powerful entity. When UID 0 requests to read, write, modify, or delete any file on any local disk, the kernel grants the request immediately, regardless of what the file's permission string says.

Root can:

  • Read and modify any file on the system, including sensitive password hashes and cryptographic keys.
  • Kill any running process, including the init system (systemd / PID 1).
  • Bind network sockets to low-numbered privileged ports (ports below 1024, like port 80 or port 443).
  • Load and unload kernel modules directly into running memory.
  • Format, partition, and wipe physical storage devices.

The Problem with Working as Root

When you log in directly as root (for example, running su - or connecting via ssh root@server), your interactive shell runs with UID 0.

Every single command you type runs with total power. That means there is no safety net.

If you make a small typo in a cleanup command while logged in as a normal user:

$ rm -rf /tmp / old-app-data/
Enter fullscreen mode Exit fullscreen mode

Notice the accidental space between /tmp and /. A normal user shell will fail when trying to delete / because a regular user does not own the root filesystem.

If you run that exact same typo while logged in as root:

# rm -rf /tmp / old-app-data/
Enter fullscreen mode Exit fullscreen mode

The shell begins deleting every file on the system starting from the root directory /. Within seconds, critical system binaries, libraries, and configurations are erased, crashing the server beyond repair.


2. What is Sudo?

The name sudo originally stood for superuser do. Today, it is more commonly described as substitute user do.

Sudo is not a user account. It is an executable binary program located at /usr/bin/sudo.

Instead of giving you a permanent superuser identity, sudo acts as a secure gateway. It allows an authorized regular user to run a specific command with elevated privileges (usually root privileges) without switching accounts or sharing root credentials.

Here is what happens when you run a command with sudo:

$ sudo systemctl restart nginx
[sudo] password for asep:
Enter fullscreen mode Exit fullscreen mode
  1. User Identity Check: Sudo identifies who is running the command (user asep).
  2. Policy Verification: Sudo reads its configuration file (/etc/sudoers) to check if asep is allowed to run /usr/bin/systemctl restart nginx on this host.
  3. Authentication: If authorized, sudo prompts for asep's personal password, not the root password.
  4. Elevation & Execution: Sudo launches the command with effective UID 0 (root).
  5. Auditing: Sudo writes a permanent log entry to the system audit logs recording who ran what command, when, and from which directory.
  6. Privilege Drop: As soon as systemctl finishes running, the elevated privileges are gone. Your shell returns to your standard unprivileged user account.

The Sudo Credential Cache

Typing your password for every single administrative command would get frustrating quickly. Sudo solves this with a configurable timestamp cache.

By default, once you successfully authenticate with sudo, it creates a secure credential ticket valid for 15 minutes.

During those 15 minutes, you can run additional sudo commands without re-entering your password. Every time you run another sudo command within the window, the 15-minute timer resets.

If you step away from your desk and want to clear the credential cache immediately for security, you can invalidate the ticket manually:

$ sudo -k
Enter fullscreen mode Exit fullscreen mode

The next time you type sudo, you will be prompted for your password again.


3. How Sudo Gets Root Powers: The SUID Bit

Have you ever wondered how a regular user can run /usr/bin/sudo and suddenly gain root permissions to inspect system files or restart services?

The secret lies in a special Linux permission called the SUID (Set User ID) bit.

Let's inspect the /usr/bin/sudo binary using ls -l:

$ ls -l /usr/bin/sudo
-rwsr-xr-x 1 root root 232416 Apr 08 2024 /usr/bin/sudo
Enter fullscreen mode Exit fullscreen mode

Look closely at the owner permissions triplet on the left: -rwsr-xr-x.

Instead of the standard x for execute, there is a lowercase s. That s is the SUID bit.

Real UID vs. Effective UID

In Linux, every running process has two main user IDs:

  • Real User ID (RUID): The ID of the actual person or account that launched the program.
  • Effective User ID (EUID): The ID that the Linux kernel uses to check permissions during execution.

Normally, when you run a program like nano or python3, both your RUID and your EUID match your regular account (e.g., UID 1000).

However, when a binary file has the SUID bit enabled and is owned by root, the kernel does something special: it sets the Effective User ID (EUID) to 0 (root) when the binary executes, while keeping your Real UID as your normal user account.

This gives the sudo binary the kernel authority to verify credentials, read the protected /etc/sudoers configuration file, switch process credentials, and execute the requested command as root.


4. Sudo vs Root: The Core Differences

To clearly see why production environments use sudo instead of root logins, let's compare both approaches across six vital operational dimensions.

1. Password and Authentication

  • Root Login: Requires everyone who needs admin rights to know the master root password. When an engineer leaves the team, you have to change the root password across every server in your fleet.
  • Sudo Delegation: Users authenticate using their own personal account passwords (or SSH keys). You never share root passwords, and revoking someone's admin access is as simple as removing them from the sudo or wheel group.

2. Scope and Session Duration

  • Root Login: Creates a continuous, persistent superuser shell session. Every single command you run, including simple directory navigation (cd) or file listings (ls), runs with full UID 0 privileges.
  • Sudo Delegation: Applies elevated privileges only to the specific command being executed. The moment that single command completes, you are back to your safe, non-privileged user account.

3. Audit Trail and Accountability

  • Root Login: In a shared root session, system logs only show that "root" ran a command. If someone accidentally deletes a database or changes a firewall rule, you cannot tell which team member performed the action.
  • Sudo Delegation: Every sudo command is explicitly recorded in system logs with the real username, terminal tty, working directory, and exact command string.

4. Principle of Least Privilege

  • Root Login: All or nothing. You cannot give someone root access to restart Nginx without also giving them the ability to read all user databases and modify kernel parameters.
  • Sudo Delegation: Highly granular. Through the /etc/sudoers file, you can allow a developer to run systemctl restart nginx and journalctl -u nginx while denying access to all other administrative commands.

5. Environment Sanitization

  • Root Login: Inherits or customizes full root environment variables, which can lead to unpredictable behavior if user-defined paths or aliases carry over.
  • Sudo Delegation: By default, sudo enables env_reset. It strips dangerous user environment variables (like LD_PRELOAD or custom PATH overrides) before running the command, protecting the system from privilege escalation attacks.

6. Account Protection and Remote Attack Surface

  • Root Login: Automated brute-force botnets on the internet constantly attack SSH port 22 attempting to log into the root username.
  • Sudo Delegation: Best practice setups disable direct root SSH logins entirely. Attackers must first guess a valid individual username before they can even attempt to authenticate.

5. The Power of /etc/sudoers and visudo

All sudo permissions and security policies are defined in a single configuration file: /etc/sudoers, along with modular configuration files inside the /etc/sudoers.d/ directory.

Why You Must Always Use visudo

Never edit /etc/sudoers with regular text editors like nano /etc/sudoers or vim /etc/sudoers.

If you make a single syntax error in /etc/sudoers (such as a missing comma or a typo in a username), sudo will fail to parse the file. When sudo breaks, no one on the system can use sudo anymore. If direct root login is disabled, you can easily lock yourself out of your own cloud server.

Instead, always edit the file using the dedicated tool:

$ sudo visudo
Enter fullscreen mode Exit fullscreen mode

visudo opens the configuration file in a safe temporary lockfile. When you save and attempt to exit, visudo parses the syntax. If it detects an error, it refuses to save, warns you of the exact line number, and gives you a chance to fix the mistake before it touches the real /etc/sudoers file.

Understanding Sudoers Syntax

The basic syntax of a rule in /etc/sudoers follows this format:

who where = (as_whom) what
Enter fullscreen mode Exit fullscreen mode

Let's look at the default rule found on most Ubuntu and Debian systems:

%sudo   ALL=(ALL:ALL) ALL
Enter fullscreen mode Exit fullscreen mode

Let's break down what each piece means:

  • %sudo: The % symbol means this rule applies to a group rather than a single user. Anyone in the sudo group gets these permissions. (On Red Hat and CentOS, the group is named %wheel).
  • ALL=: The first ALL defines the network hosts where this rule applies. ALL means this rule works on any hostname or machine.
  • (ALL:ALL): The targets in parentheses define who the user can run commands as. The first ALL means any user (including root); the second ALL means any group.
  • ALL: The final ALL specifies which commands the user is allowed to run. ALL means any executable binary on the system.

Creating Granular Permissions for Team Members

In real-world teams, you often want junior engineers or developers to manage specific services without giving them full system access.

Using sudo visudo, you can add safe, targeted rules at the bottom of the file (or inside /etc/sudoers.d/developer-rules):

# Allow developer asep to restart web services and check logs
asep ALL=(ALL) /usr/bin/systemctl restart nginx, /usr/bin/systemctl reload nginx, /usr/bin/journalctl
Enter fullscreen mode Exit fullscreen mode

With this rule in place, user asep can run:

$ sudo systemctl restart nginx
Enter fullscreen mode Exit fullscreen mode

If asep tries to run an unauthorized command:

$ sudo apt install htop
Sorry, user asep is not allowed to execute '/usr/bin/apt install htop' as root on webserver01.
Enter fullscreen mode Exit fullscreen mode

The attempt is immediately blocked and logged to the security audit trail.

Granting Commands Without Password Prompts

For automated deployment scripts or monitoring agents, you can use the NOPASSWD tag so background automation can run specific checks without hanging on an interactive password prompt:

# Allow backup user to run rsync as root without a password
backupuser ALL=(root) NOPASSWD: /usr/bin/rsync
Enter fullscreen mode Exit fullscreen mode

6. Demystifying su, su -, sudo -s, and sudo -i

One of the most confusing areas for Linux users is the alphabet soup of shell-switching commands: su, su -, sudo -s, and sudo -i.

While they all give you an administrative root prompt (#), they behave very differently behind the scenes.

Let's break down each one.

1. su (Switch User)

su stands for switch user. When run without arguments, it defaults to switching to the root account.

$ su
Password:
#
Enter fullscreen mode Exit fullscreen mode
  • Password required: The root account password.
  • Environment: It switches your user ID to root, but it preserves your current user's environment variables, including your $PATH, $HOME, and shell configuration.
  • Working directory: Remains in whatever directory you were in when you ran the command.
  • Risk: Because it keeps your normal user's $PATH, you might accidentally execute binaries from unprivileged user directories.

2. su - (Switch User with Full Login Shell)

Adding the hyphen (- or -l / --login) tells su to launch a completely fresh login shell.

$ su -
Password:
# pwd
/root
Enter fullscreen mode Exit fullscreen mode
  • Password required: The root account password.
  • Environment: It completely discards your old environment. It loads root's .bash_profile, sets $HOME to /root, initializes root's clean system $PATH, and moves your working directory to /root.
  • Standard use: This is the traditional Unix method for becoming root, but it requires knowing the root password.

3. sudo -s (Sudo Shell)

sudo -s runs the shell specified by your current $SHELL variable (or the shell listed in /etc/passwd) with elevated privileges.

$ sudo -s
[sudo] password for asep:
#
Enter fullscreen mode Exit fullscreen mode
  • Password required: Your personal password.
  • Environment: It runs with root privileges, but retains much of your original user environment and stays in your current directory.
  • Use case: Quick root tasks where you want to keep your current terminal location and session variables.

4. sudo -i (Sudo Login Simulation)

sudo -i simulates an initial login to the root account using sudo permissions.

$ sudo -i
[sudo] password for asep:
# pwd
/root
Enter fullscreen mode Exit fullscreen mode
  • Password required: Your personal password.
  • Environment: It completely re-initializes the environment just like su -. It loads /root/.profile and /root/.bashrc, changes the working directory to /root, and sets root's standard system path.
  • Standard use: This is the recommended modern way to get a full interactive root session when performing major system maintenance, without ever needing to know or enable a master root password.

5. sudo -u (Running as Another User)

Sudo is not just for root. You can use the -u flag to run commands as any service account on the system.

For example, when managing PostgreSQL databases, you should run commands as the postgres user:

$ sudo -u postgres psql
psql (14.11)
Type "help" for help.

postgres=#
Enter fullscreen mode Exit fullscreen mode

Or running a git maintenance task as the www-data web server account:

$ sudo -u www-data whoami
www-data
Enter fullscreen mode Exit fullscreen mode

This prevents file ownership issues and ensures files created by service accounts are not accidentally owned by root.


7. Common Traps and Gotchas with Sudo

Even experienced engineers run into these common sudo gotchas. Let's look at why they happen and how to solve them cleanly.

Gotcha 1: The Shell Redirection Trap

You want to append a new setting to a protected system file, so you run:

$ sudo echo "vm.swappiness=10" >> /etc/sysctl.conf
bash: /etc/sysctl.conf: Permission denied
Enter fullscreen mode Exit fullscreen mode

Why did this fail even though you typed sudo?

In Linux, your current shell processes I/O redirection (> and >>) before running the command.

The command echo "vm.swappiness=10" was scheduled to run with sudo, but your regular, unprivileged user shell was the one trying to open /etc/sysctl.conf for writing. Because your user account does not have write access to /etc/sysctl.conf, the shell returns "Permission denied".

The Solution: Use tee

Pipe the output to tee running under sudo:

$ echo "vm.swappiness=10" | sudo tee -a /etc/sysctl.conf
Enter fullscreen mode Exit fullscreen mode

tee runs with elevated privileges, reads from standard input, and writes directly to the protected file while also showing the output in your terminal. Use -a to append instead of overwriting.

Alternatively, execute the entire pipeline inside a subshell:

$ sudo sh -c 'echo "vm.swappiness=10" >> /etc/sysctl.conf'
Enter fullscreen mode Exit fullscreen mode

Gotcha 2: Missing Aliases Under Sudo

You create a handy alias in your ~/.bashrc:

alias ll='ls -lah --color=auto'
Enter fullscreen mode Exit fullscreen mode

When you run ll /var/log, it works. But when you try sudo ll /var/log, you get an error:

$ sudo ll /var/log
sudo: ll: command not found
Enter fullscreen mode Exit fullscreen mode

By default, bash does not expand aliases for the arguments passed to commands. Sudo looks for an actual binary program named ll on your disk and cannot find one.

The Solution: The Trailing Space Alias Trick

Add this single line to your ~/.bashrc:

alias sudo='sudo '
Enter fullscreen mode Exit fullscreen mode

In bash, if the value of an alias ends with a space, the shell checks the next word on the command line for alias expansion as well.

Once you add that trailing space, sudo ll will properly expand ll into ls -lah before running!

Gotcha 3: The Dangerous Habit of "sudo su"

You often see tutorials tell users to type:

$ sudo su
Enter fullscreen mode Exit fullscreen mode

While this works, it is redundant and messy. You are using sudo (which runs a command as root) to execute su (which switches to root).

If you need a persistent root shell, use the clean, native command:

$ sudo -i
Enter fullscreen mode Exit fullscreen mode

sudo -i properly initializes the environment and avoids spawning nested authentication layers.


8. Auditing and Security Logs

One of the biggest advantages of sudo over direct root logins is the audit trail.

Whenever a user executes a command with sudo, Linux records the transaction. On Debian and Ubuntu systems, authentication logs are stored in /var/log/auth.log. On Red Hat, Fedora, and Rocky Linux, they are stored in /var/log/secure. On modern systemd systems, you can view them with journalctl.

Let's inspect what a sudo log entry looks like:

$ sudo journalctl -u sudo -n 5 --no-pager
Enter fullscreen mode Exit fullscreen mode

Output:

Aug 20 14:15:02 webserver01 sudo[18492]:     asep : TTY=pts/0 ; PWD=/home/asep ; USER=root ; COMMAND=/usr/bin/systemctl restart nginx
Aug 20 14:18:22 webserver01 sudo[18530]:     asep : TTY=pts/0 ; PWD=/var/www/html ; USER=root ; COMMAND=/usr/bin/vim index.html
Aug 20 14:22:10 webserver01 sudo[18604]:  johndoe : user NOT in sudoers ; TTY=pts/1 ; PWD=/home/johndoe ; USER=root ; COMMAND=/usr/bin/cat /etc/shadow
Enter fullscreen mode Exit fullscreen mode

Look at the valuable information in every single line:

  • Timestamp and Hostname: When and where the event occurred (Aug 20 14:15:02 webserver01).
  • Invoking User: The exact individual user who ran the command (asep).
  • TTY and Working Directory: The terminal session and directory path (TTY=pts/0, PWD=/home/asep).
  • Target User: Who they ran the command as (USER=root).
  • Exact Command: The exact binary and arguments executed (COMMAND=/usr/bin/systemctl restart nginx).
  • Security Alerts: If an unauthorized user tries to use sudo (johndoe : user NOT in sudoers), it logs a security violation so intrusion detection systems and Prometheus alerts can notify your team.

If everyone logs in directly as root over SSH, your logs would only show actions by root, making post-incident forensics nearly impossible.


9. Interesting Fact

The sudo program was created in 1980 by Bob Coggeshall and Cliff Spencer at the Department of Computer Science at SUNY Buffalo.

Back then, computer science students and lab assistants frequently needed to perform routine administrative maintenance, like unjamming line printer queues, mounting backup magnetic tapes, and managing shared disk volumes on PDP-11 and VAX minicomputers.

Before sudo, the only way to let an assistant mount a tape was to give them the master root password. Once they had the root password, they had full control over every student record, exam file, and system daemon on the entire machine.

Coggeshall and Spencer wrote the first version of sudo to create a limited "operator" delegation mechanism, allowing specific users to run only the tape and printer commands with root privileges while protecting the rest of the operating system.

In 1991, Todd C. Miller took over development and maintenance of sudo, expanding it into the security tool installed on virtually every Linux distribution and macOS system in the world today.


10. Production Best Practices for Superuser Access

To keep your servers secure, stable, and compliant with modern security standards, follow these seven golden rules:

  1. Disable Root SSH Logins: Edit /etc/ssh/sshd_config and set PermitRootLogin no. Force every administrator to connect using their personal user account and SSH key, then use sudo for privileged tasks.
  2. Lock the Root Account Password: On Ubuntu and cloud images, the root account password is locked by default. Keep it locked with sudo passwd -l root. Users should elevate via sudo instead of switching accounts with a master password.
  3. Always Use visudo: Never edit /etc/sudoers or /etc/sudoers.d/* with standard text editors. Always let visudo validate your syntax.
  4. Use Drop-In Sudoers Files: Instead of modifying the main /etc/sudoers file directly, create modular configuration files inside /etc/sudoers.d/ (e.g., /etc/sudoers.d/99-dev-team). Ensure permissions are set to 0440.
  5. Apply the Principle of Least Privilege: Do not hand out full ALL=(ALL) ALL privileges by default. Restrict junior staff, CI/CD runners, and background service scripts to the exact commands they need.
  6. Never Run Package Managers Blindly as Root: Avoid running commands like sudo pip install or sudo npm install -g unless strictly necessary. Use virtual environments (venv) or local user directories to prevent third-party scripts from running arbitrary install hooks as root.
  7. Monitor Sudo Logs: Connect your server's authentication logs (/var/log/auth.log or journalctl) to a centralized log management tool or SIEM (like Grafana Loki, Elasticsearch, or Wazuh) to get real-time alerts on unauthorized sudo attempts.

Key Takeaways

The difference between sudo and root comes down to identity versus delegation:

  1. Root is an Identity (UID 0): The all-powerful superuser account that bypasses standard Linux filesystem permissions.
  2. Sudo is a Security Tool: An SUID binary that temporarily delegates root privileges for single commands based on policy rules.
  3. Sudo Protects Credentials: Users authenticate with their own password, meaning the root password never needs to be shared or distributed.
  4. Sudo Provides Accountability: Every privileged command is logged with the user's real username, timestamp, and command arguments.
  5. Sudo Prevents Disasters: By restricting elevated permissions to individual commands, sudo protects your system from accidental typos and persistent runaway scripts.

Treating root privileges with respect and using sudo thoughtfully is what separates casual terminal users from professional Linux engineers.


How Do You Manage Superuser Access?

Do you enforce strict command-level rules in your /etc/sudoers.d/ directory, or do you rely on standard group access? Have you ever had a close call with an accidental command run under root? Share your experience in the comments below!


About the Author

Asep Sayyad is a Linux and DevOps engineer passionate about Linux administration, automation, cloud technologies, containers, and open-source software. He enjoys solving real-world infrastructure challenges and sharing practical knowledge through in-depth technical articles, tutorials, and hands-on guides.

His goal is to help aspiring and experienced engineers build stronger Linux and DevOps skills with content focused on real production scenarios rather than theory alone.

Connect with Me

Portfolio: https://asepsayyad007.in
GitHub: https://github.com/asepsayyad007
LinkedIn: https://www.linkedin.com/in/asepsayyad
Medium: https://asepsayyad007.medium.com

Enjoyed this article?

If you found this guide helpful, consider:

  • Starring my open-source projects on GitHub.
  • Sharing this article with fellow Linux and DevOps engineers.

You can also follow me for more practical content on Linux, DevOps, Cloud, Containers, Automation, and Open Source. Thanks for reading, and enjoy your learning!

© 2026 Asep Sayyad

Top comments (1)

Collapse
 
freerave profile image
freerave

Really good breakdown — especially the identity vs delegation distinction.

One thing I'm curious about though: when you build tightly scoped sudoers rules, how do you reason about transitive privilege?

For example, a user may only be allowed to run one specific binary as root, but that binary might load configs, invoke subprocesses, open a pager/editor, or operate on files the user can influence.

At that point, do you still consider command-level allowlisting sufficient, or do you treat the entire execution path of the allowed binary as part of the privilege boundary?