What Is the Difference Between su and sudo?
su opens a root shell by switching user account (requires root password). sudo runs a single command as root using your password, with per-command privileges and audit logging. See
Sponsor message — This article is made possible by Dargslan.com, a publisher of practical, no-fluff IT & developer workbooks.
Why Dargslan.com?
If you prefer doing over endless theory, Dargslan’s titles are built for you. Every workbook focuses on skills you can apply the same day—server hardening, Linux one-liners, PowerShell for admins, Python automation, cloud basics, and more.
Understanding su and sudo Commands
System administration in Linux and Unix-based operating systems requires elevated privileges for critical tasks, and understanding how to properly escalate permissions can mean the difference between a secure, well-managed system and a vulnerable one. Every system administrator, developer, and power user encounters situations where standard user permissions simply aren't enough to complete essential operations. Whether you're installing software, modifying system configurations, or managing user accounts, you'll need to temporarily or permanently operate with higher-level access rights.
Two fundamental commands serve as gateways to administrative power in Unix-like systems: su (substitute user) and sudo (superuser do). While both commands grant elevated privileges, they operate on distinctly different principles, offer varying levels of security, and suit different administrative philosophies. Understanding these differences isn't merely academic—it directly impacts your system's security posture, audit capabilities, and operational efficiency.
This comprehensive exploration will guide you through the technical distinctions, practical applications, security implications, and best practices for both commands. You'll discover when to use each tool, how they differ in authentication mechanisms, their respective advantages and limitations, and how modern Linux distributions have shaped their implementation. By the end, you'll possess the knowledge to make informed decisions about privilege escalation in your own environments.
Understanding the Fundamental Concepts
The su command represents one of the oldest methods of privilege escalation in Unix systems, dating back to the earliest versions of the operating system. The name literally means "substitute user" or "switch user," though it's commonly understood as "superuser" when used without arguments. When you execute su, you're requesting to become another user entirely—typically the root user—which requires knowing that target user's password. This complete identity switch means you inherit all of that user's environment variables, permissions, and access rights.
In contrast, sudo takes a fundamentally different approach to privilege management. Rather than switching user identities, sudo allows permitted users to execute specific commands with elevated privileges while maintaining their own identity. The authentication happens through your own password, not the root password, and the system maintains detailed logs of who executed what command and when. This command-by-command authorization model emerged from the need for more granular control over administrative access.
"The greatest security risk isn't the tool you use, but understanding when and how to use it appropriately."
Authentication Mechanisms
The authentication differences between these commands reveal their underlying philosophies. When you use su, the system prompts for the password of the user you're switching to. If you're switching to root, you need the root password. This creates an immediate security consideration: the root password must be shared among all administrators who need occasional elevated access. Each person who knows this password has complete, unrestricted access to the entire system.
The sudo approach eliminates password sharing entirely. Each user authenticates with their own password, and the system consults a configuration file (typically /etc/sudoers) to determine whether that user has permission to execute the requested command. This configuration can be incredibly granular, specifying exactly which commands each user or group can execute, on which hosts, and even as which target users. The system caches your authentication for a configurable period (usually 15 minutes by default), so you don't need to re-enter your password for every subsequent sudo command.
Security Implications and Best Practices
From a security perspective, the differences between su and sudo extend far beyond simple authentication. The principle of least privilege—a fundamental security concept stating that users should have only the minimum access necessary to perform their duties—is much easier to implement with sudo. When someone uses su to become root, they gain unrestricted access to everything on the system until they explicitly exit that shell session. During that entire period, every command executes with root privileges, whether it needs them or not.
Consider a scenario where an administrator needs to edit a configuration file, restart a service, and check system logs. Using su, they might switch to root, perform these tasks, and ideally remember to exit the root shell when finished. However, human nature means that root shell might remain open while they check documentation, answer emails, or grab coffee. That open root terminal represents a significant security exposure—any command typed there, including mistakes, executes with full system privileges.
| Security Aspect | su Command | sudo Command |
|---|---|---|
| Password Required | Target user's password (usually root) | Your own password |
| Password Sharing | Root password must be known by all admins | No password sharing needed |
| Privilege Scope | Complete access until exit | Per-command authorization |
| Audit Trail | Shows only who switched to root | Logs every command executed |
| Granular Control | All-or-nothing access | Configurable per user/command |
| Session Duration | Until explicitly terminated | Individual command execution |
Accountability and Auditing
The auditing capabilities represent another critical distinction. When multiple administrators share the root password and use su, the system logs show only that someone became root—not who that someone was or what they did while operating as root. This creates significant accountability gaps. If a configuration error appears or unauthorized changes occur, determining which administrator made those changes becomes difficult or impossible.
"Accountability isn't about distrust; it's about creating an environment where mistakes can be traced, learned from, and prevented in the future."
With sudo, every privileged command execution generates a log entry containing the username of who executed it, what command they ran, when they ran it, and from which directory. This detailed audit trail proves invaluable for security investigations, compliance requirements, and simple troubleshooting. When something goes wrong, you can quickly identify which administrative action caused the issue and who performed it. This isn't about blame—it's about understanding system changes and maintaining operational awareness.
Practical Usage Patterns
Understanding the syntax and practical applications of each command helps clarify when to use which tool. The su command in its simplest form appears as just "su" at the command prompt. This switches you to the root user while preserving your current environment variables. To get a complete root environment—including root's PATH, HOME, and other settings—you use "su -" or "su -l" (the hyphen or -l flag indicates a login shell). You can also switch to any other user by specifying their username: "su - username".
Common su Usage Examples
- 🔐 su - Switch to root user, keeping current environment
- 🏠 su - - Switch to root with root's full environment (login shell)
- 👤 su - username - Switch to specific user with their environment
- ⚡ su -c "command" - Execute single command as root, then return
- 🔄 su -s /bin/bash username - Switch to user with specified shell
The sudo command typically precedes the command you want to execute with elevated privileges. "sudo apt update" runs the apt update command as root. "sudo systemctl restart nginx" restarts the nginx service with administrative privileges. For situations requiring multiple privileged commands, "sudo -i" or "sudo -s" opens an interactive root shell, though this somewhat defeats sudo's per-command authorization model.
Common sudo Usage Examples
- ⚙️ sudo command - Execute single command with root privileges
- 📝 sudo -e /etc/config - Edit file with elevated privileges using your EDITOR
- 👥 sudo -u username command - Execute command as specified user
- 💻 sudo -i - Start interactive root shell (login shell)
- 🛠️ sudo -s - Start root shell with current environment
"The best security tool is the one that matches your operational needs while minimizing risk exposure."
Configuration and Customization
The flexibility of sudo comes from its configuration file, /etc/sudoers. This file determines who can execute what commands with elevated privileges. Editing this file requires special care—you should always use the "visudo" command, which provides syntax checking to prevent configuration errors that could lock you out of administrative access. The sudoers file uses a specific syntax that allows incredibly detailed permission specifications.
A basic sudoers entry might look like "username ALL=(ALL:ALL) ALL", which grants the specified user permission to execute any command as any user on any host. More restrictive configurations might specify "username ALL=/usr/bin/systemctl restart nginx", allowing that user to restart nginx but nothing else. You can create command aliases, user aliases, and host aliases to manage complex permission structures across multiple systems and administrators.
| Configuration Element | Purpose | Example |
|---|---|---|
| User Specification | Defines who can use sudo | john ALL=(ALL) ALL |
| Command Aliases | Groups commands together | Cmnd_Alias NETWORKING = /sbin/route, /sbin/ifconfig |
| User Aliases | Groups users together | User_Alias ADMINS = john, jane, bob |
| NOPASSWD Option | Allows commands without password | username ALL=(ALL) NOPASSWD: /usr/bin/systemctl |
| Runas Specification | Specifies which users can be impersonated | username ALL=(webuser) /var/www/scripts/* |
Environment Variables and Security
Both commands handle environment variables differently, with important security implications. When using su without the hyphen, you retain your current environment variables. This can lead to unexpected behavior or security issues—for example, your regular user's PATH might be used instead of root's, potentially causing commands to execute from unexpected locations. Using "su -" solves this by loading root's complete environment, but means you need to be aware that your current working directory and other context will change.
The sudo command takes a security-focused approach to environment variables. By default, it resets most environment variables and uses a restricted set defined in the sudoers configuration. The env_reset option (enabled by default in most distributions) clears potentially dangerous variables. However, certain variables like TERM, PATH, and others in the env_keep list are preserved. You can pass specific environment variables through sudo using the -E flag, but this requires appropriate sudoers permissions.
Distribution-Specific Implementations
Different Linux distributions have adopted varying approaches to these commands, reflecting different security philosophies. Ubuntu and its derivatives famously disabled the root account by default, making sudo the primary method for administrative tasks. When you install Ubuntu, the first user created is automatically added to the sudo group with full administrative privileges. This design choice emphasizes the sudo model and encourages per-command privilege escalation.
Traditional distributions like Debian, Red Hat, and CentOS historically enabled the root account during installation and expected administrators to use su for privilege escalation. However, even these distributions have increasingly embraced sudo, with newer versions offering it as an option during installation. Modern Fedora installations, for example, can be configured either way depending on administrator preference.
"System security is not about choosing the most restrictive tool, but about choosing the right tool for your specific operational and security requirements."
Corporate and Enterprise Environments
In enterprise environments, sudo has become the overwhelming favorite due to its superior auditing, accountability, and integration with centralized authentication systems. Large organizations can configure sudo to work with LDAP, Active Directory, or other directory services, allowing centralized management of administrative permissions across hundreds or thousands of systems. The detailed logging integrates with security information and event management (SIEM) systems, providing comprehensive visibility into privileged operations.
Some organizations implement sudo with additional layers of security, such as requiring two-factor authentication for privileged commands or implementing approval workflows where certain high-risk commands require authorization from a second administrator before execution. These advanced configurations would be impossible or extremely difficult to implement with su.
Performance and Resource Considerations
From a performance perspective, both commands introduce minimal overhead. The su command creates a new shell process running as the target user, which consumes some memory and CPU cycles but is negligible on modern systems. The shell remains active until you exit it, maintaining that resource allocation for the duration of your administrative session.
The sudo command creates a new process for each command execution, which technically involves slightly more overhead than running multiple commands in a single su shell. However, this overhead is measured in milliseconds and is imperceptible in practical use. The authentication caching mechanism means you don't pay the password verification cost for every command within the timeout period. For automated scripts or system processes, sudo can be configured with NOPASSWD options to eliminate authentication entirely for specific commands.
Common Mistakes and Misconceptions
Many users mistakenly believe that sudo is inherently more secure than su simply because it's the newer tool. Security depends entirely on configuration and usage patterns. A user with "ALL=(ALL) NOPASSWD: ALL" in their sudoers file has exactly the same unrestricted access as someone who knows the root password and uses su. The security benefits of sudo come from proper configuration—limiting permissions to necessary commands, requiring password authentication, and maintaining detailed audit logs.
Another common misconception involves the "sudo su" command combination. Some users execute "sudo su" to get a root shell, thinking this is somehow better than using su directly. In reality, this combines the worst aspects of both approaches—you're using sudo to execute su, which then creates a root shell. This defeats sudo's per-command authorization model while still requiring sudo permissions. If you need an interactive root shell with sudo, "sudo -i" or "sudo -s" are more appropriate choices.
"Understanding the tools you use daily transforms you from someone who follows commands to someone who makes informed security decisions."
Password Security Considerations
The root password in su-based systems represents a single point of failure. If compromised, an attacker has complete system access. When administrators leave an organization, the root password must be changed across all systems they accessed. This password rotation can be complex and error-prone in large environments. Additionally, the shared nature of the root password makes it more likely to be written down, shared insecurely, or chosen to be simpler than it should be for memorability.
With sudo, each administrator maintains their own password and credentials. When someone leaves, you simply remove their account or sudo permissions—no password changes required. If one account is compromised, the attacker gains only that user's specific sudo permissions, not complete system access. Individual passwords can be as complex as needed since each person only needs to remember their own.
Scripting and Automation
For scripting purposes, both commands present challenges and solutions. Using su in scripts typically requires handling password input, which is problematic for automation. You can't simply embed the root password in a script for security reasons. Some solutions involve expect scripts or SSH key-based authentication, but these add complexity and potential security vulnerabilities.
The sudo approach to scripting is more straightforward when properly configured. Scripts can be configured in sudoers to run specific commands without password prompts using NOPASSWD. This allows automated processes to execute privileged operations while maintaining detailed audit logs of what ran and when. The granular permission model means you can allow a script to restart a specific service without granting it broader system access.
Migration Strategies
Organizations moving from su-based administration to sudo-based models should approach the transition methodically. Start by identifying all administrative tasks and the users who perform them. Document which commands require elevated privileges and create appropriate sudoers configurations that grant necessary permissions without over-provisioning access. Implement sudo alongside existing su access initially, allowing administrators to become comfortable with the new approach before removing su access entirely.
Training is crucial during this transition. Administrators accustomed to working in root shells need to adapt their workflows to the per-command sudo model. This includes understanding how to use sudo with pipes and redirects (which can be tricky since the shell interprets these before sudo sees them), how to edit files with elevated privileges, and how to troubleshoot permission issues. The investment in training pays dividends in improved security and operational visibility.
Advanced Use Cases
Both commands support advanced scenarios beyond basic privilege escalation. The su command can switch to any user, not just root, which is useful for testing applications under different user contexts or troubleshooting permission issues. System administrators might use "su - webuser" to verify that web application files have correct permissions and that the application can access necessary resources.
Similarly, sudo supports running commands as any user through the -u option. "sudo -u postgres psql" executes the PostgreSQL command-line tool as the postgres user. This capability is valuable for managing services that run under specific user accounts or for testing application behavior in different security contexts. The sudoers configuration can specify exactly which users can impersonate which other users, providing fine-grained control over these operations.
Security Hardening Recommendations
Regardless of which command you primarily use, several security hardening practices apply. For su, restrict which users can even attempt to use the command by configuring PAM (Pluggable Authentication Modules) to limit su access to members of a specific group (traditionally called "wheel"). Set strong password policies for the root account, and consider disabling root login entirely for remote access, requiring administrators to log in with personal accounts first.
For sudo, review and minimize permissions regularly. Follow the principle of least privilege by granting only necessary command access. Enable detailed logging and regularly review sudo logs for suspicious activity. Set appropriate timeout values for password caching—shorter timeouts increase security but decrease convenience. Consider implementing two-factor authentication for sudo operations in high-security environments. Use command aliases and structured sudoers files to maintain clarity and prevent configuration errors.
Can I use sudo if my system only has su configured?
Yes, you can install and configure sudo on any Linux system even if it currently uses only su. Most distributions include sudo in their package repositories. After installation, you'll need to configure the /etc/sudoers file (using visudo) to grant appropriate permissions to users who should have sudo access. This can be done alongside existing su access, allowing a gradual transition.
Why does Ubuntu disable the root account by default?
Ubuntu disables the root account to encourage the use of sudo for administrative tasks, which provides better security through accountability and audit trails. Users cannot log in directly as root, which prevents certain types of attacks and misconfigurations. Administrative tasks are performed through sudo, which logs all privileged operations. If you absolutely need root access, you can enable the account by setting a root password, though this is not recommended for most users.
Is it safe to use NOPASSWD in sudoers configuration?
Using NOPASSWD in sudoers removes password authentication for specified commands, which reduces security but may be necessary for automation or specific use cases. It's safe when properly scoped—for example, allowing a monitoring script to check service status without a password is reasonable. However, granting NOPASSWD for all commands or dangerous operations creates significant security risks. Always limit NOPASSWD to specific, necessary commands and ensure the user account itself is properly secured.
What happens if I make a mistake in the sudoers file?
If you edit /etc/sudoers directly and introduce syntax errors, you could lock yourself out of administrative access. This is why you should always use the visudo command to edit sudoers—it performs syntax checking before saving changes. If errors are detected, visudo prompts you to fix them before allowing the file to be saved. If you somehow end up with a broken sudoers file, you'll need to boot into recovery mode or single-user mode to fix it.
Can sudo and su be used together in the same system?
Yes, both commands can coexist and function independently on the same system. Many distributions have both available, and administrators can choose which to use based on the situation. Some administrators use sudo for routine tasks and reserve su for situations requiring extended root access. However, for security and consistency, most organizations standardize on one approach—typically sudo—to simplify auditing and permission management.
How do I check what sudo permissions I have?
Use the command "sudo -l" to list all sudo privileges granted to your current user. This displays which commands you can execute with sudo, whether password authentication is required, and any other relevant restrictions. This is helpful for understanding your current permissions or troubleshooting why a particular sudo command isn't working. The output format matches the sudoers file syntax, showing exactly what permissions have been configured for your account.