Website Vidya
SecurityStep-by-Step Guide

su Command in Linux: Switch Users and Run Commands with Substitute Identity

Learn su command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.

RR
Rajesh RayLead Systems Educator
Published:
12 min read
PDF Cheat Sheet
su Command in Linux: Switch Users and Run Commands with Substitute Identity
AI Executive SummaryWebsiteVidya AI

12 min read

Learn su command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.

Key Highlights
  • What su Does and When to Use It
  • Availability and Installation Across Linux Distributions
  • Command Syntax, Arguments, and Exit Status Codes
Grounded in full engineering runbookWebsiteVidya AI Engine

Mastering su command in linux is an essential skill for Linux system administrators, developers, and DevOps engineers. Understanding the su command in Linux is essential for system administrators troubleshooting service permissions, testing application environments, and performing root maintenance on servers where sudo is not configured. Short for substitute user (or switch user), su launches a new shell session or executes a single command (-c) with the effective and real UID, GID, and supplementary groups of another account.

The single most important detail when using the su command in Linux is the difference between su username and su - username (also written su -l username or su --login username). Running su username without the hyphen spawns a non-login shell that switches the numeric UID/GID but retains the calling user's working directory (PWD), HOME, USER, and PATH variables—a hybrid state that frequently breaks scripts and pollutes dotfiles with wrong ownership. Passing - (su - username) simulates a full, clean login as the target user.

When invoked by root (or via sudo su - username), su switches directly to the target account without prompting for a password. Even if the target service account has /usr/sbin/nologin or /bin/false configured in /etc/passwd, administrators can pass -s /bin/bash to open a diagnostic shell as www-data, postgres, or nginx.

Advertisement
su Command in Linux: Switch Users and Run Commands with Substitute Identity — syntax, flags, and practical terminal workflow diagram
su Command in Linux: Switch Users and Run Commands with Substitute Identity — command syntax, key options, and production workflow reference.

What su Does and When to Use It

Modern Linux distributions ship the su implementation maintained in util-linux (which unified the historic GNU coreutils and shadow-utils implementations). Because su must allow an unprivileged user to transition to another UID after authenticating, the /usr/bin/su binary is installed with the setuid root permission bit (-rwsr-xr-x 1 root root). When executed, su invokes the Pluggable Authentication Modules (PAM) stack defined in /etc/pam.d/su (and /etc/pam.d/su-l for login shells).

Notice how authentication differs between su and sudo: when an unprivileged user runs su - bob, PAM prompts for bob's password (or root's password if running su -). By contrast, sudo prompts for the calling user's own password and checks authorization rules in /etc/sudoers. On Ubuntu and many cloud images where the root password hash in /etc/shadow is locked (!) by default, su - will always return Authentication failure unless invoked via sudo su - or sudo -i.

Linux enforces discretionary access control (DAC) by evaluating the effective User ID (EUID), effective Group ID (EGID), and supplementary groups against inode permission bits. When su executes, the Virtual File System (VFS) and active Linux Security Modules (SELinux or AppArmor) validate the caller's privileges before committing changes to disk or account databases.

Availability and Installation Across Linux Distributions

The su utility is packaged in util-linux across mainstream Linux distributions. It is pre-installed on standard Ubuntu, Debian, RHEL, Rocky Linux, AlmaLinux, Fedora, and Arch Linux systems, while minimal container images may require manual installation:

Advertisement

Before running administrative tasks or automation scripts, verify whether su is installed and inspect which binary path and version your shell resolves:

type -a su
su --version 2>/dev/null || man -f su

# Illustrative output (reviewed against documentation)
su is /usr/bin/su
su (util-linux)
# Debian / Ubuntu
sudo apt-get update && sudo apt-get install -y util-linux

# RHEL / Rocky / AlmaLinux / Fedora
sudo dnf install -y util-linux

# Arch Linux
sudo pacman -S --noconfirm util-linux

# Alpine Linux
sudo apk add --no-cache util-linux-misc

Command Syntax, Arguments, and Exit Status Codes

su [OPTIONS] [-] [USERNAME [ARGUMENTS...]]

The syntax su [OPTIONS] [-] [USERNAME [ARG...]] treats both USERNAME and - as optional. If USERNAME is omitted, su defaults to root. The standalone hyphen - is a POSIX shorthand for -l / --login, and by convention is placed immediately before the username (su - postgres).

To run a single non-interactive command as another user and immediately return to your current shell, pass -c "COMMAND" (--command="COMMAND"). Remember that the entire command string passed to -c is handed to the target user's shell (sh -c), so complex pipelines or quotes should be wrapped carefully.

  • 0 — Target shell or command exited with status 0.
  • 1 — Generic error before executing the target shell (such as PAM Authentication failure or invalid user).
  • 126 — The requested shell binary was found on disk but could not be executed (permission denied).
  • 127 — The requested shell binary does not exist on the system.
  • N — If the target shell or -c command runs and exits with non-zero status N, su propagates exit code N.

Important Options and Flags Reference

Option / FlagLong Form / ArgumentTechnical Behavior and Purpose
-, -l--loginStart the shell as a full login shell: clear environment variables, initialize HOME/SHELL/USER/LOGNAME/PATH, and cd to the target user's home directory.
-c--command COMMANDPass a single COMMAND string to the target user's shell via its -c option instead of starting an interactive session.
-s--shell SHELLRun the specified SHELL binary instead of the default shell listed in /etc/passwd ( useful for nologin service accounts).
-m, -p--preserve-environmentPreserve the entire calling environment (HOME, SHELL, USER, LOGNAME) when switching users.
-w--whitelist-environment LISTWhen using -l (--login), preserve a comma-separated list of specific environment variables from the caller.
-g--group GROUPSpecify the primary group for the switched session (accessible to root only).
-G--supp-group GROUPSpecify a supplementary group for the switched session (accessible to root only).
-P--ptyCreate a new pseudo-terminal (PTY) for the session to prevent TIOCSTI terminal injection attacks from unprivileged child processes.

Always make su - (with the hyphen) your muscle memory. Without -, su leaves you standing in the previous user's current directory with the previous user's $HOME variable; if you run an interactive editor or tool that writes a cache file to $HOME/.config, you can accidentally create root-owned files inside an unprivileged user's home directory!

Advertisement

When switching from root to an unprivileged or untrusted service account to run a command, add the -P (--pty) flag (su -P -s /bin/bash - www-data). Historically, if root ran su - www-data inside the same controlling terminal without allocating a new pseudo-terminal, a malicious process running as www-data could use the TIOCSTI ioctl syscall to stuff keystrokes back into root's terminal input buffer.

When combining short flags on the command line, POSIX and GNU utilities allow clustering boolean flags behind a single hyphen, provided any option taking an argument appears last. In automated shell scripts, using long-form GNU options where portable makes self-documenting code that is easier to audit during peer review.

Practical Basic and Advanced Usage Examples

1. Switch to a Another User with a Full Login Environment (su -)

Use su - username to open an interactive login shell initialized with username's home directory, $PATH, and .bash_profile / .profile settings.

su - alex
pwd
whoami
env | grep -E '^(USER|HOME|LOGNAME|SHELL)='
exit

# Illustrative output (reviewed against documentation)
Password: 
/home/alex
alex
USER=alex
HOME=/home/alex
LOGNAME=alex
SHELL=/bin/bash
logout

Because - was passed, su cleared the previous environment, initialized USER, HOME, and LOGNAME to alex, changed the working directory to /home/alex, and sourced login dotfiles.

2. Compare Non-Login 'su' vs Login 'su -'

Observe how omitting the - flag leaves $HOME and the working directory unchanged.

# Starting as user 'ubuntu' in /home/ubuntu:
su alex -c 'echo "UID=$(id -un) HOME=$HOME PWD=$PWD"'
su - alex -c 'echo "UID=$(id -un) HOME=$HOME PWD=$PWD"'

# Illustrative output (reviewed against documentation)
Password: 
UID=alex HOME=/home/alex PWD=/home/ubuntu
Password: 
UID=alex HOME=/home/alex PWD=/home/alex

Without -, the current working directory (PWD=/home/ubuntu) and non-essential environment variables carry over from ubuntu, where alex does not even have read/write permissions.

3. Run a Single Command as Another User (-c)

Execute a database backup or check an application configuration file as the postgres user without remaining in an interactive subshell.

sudo su - postgres -c "psql -c 'SELECT version();'"

# Illustrative output (reviewed against documentation)
version                                                 
---------------------------------------------------------------------------------------------------------
 PostgreSQL 16.4 (Ubuntu 16.4-1.pgdg24.04+1) on x86_64-pc-linux-gnu, compiled by gcc 13.2.0, 64-bit
(1 row)

Invoking sudo su - postgres -c "..." transitions to root via sudo, switches cleanly to a postgres login environment without requiring a postgres password, runs psql, and returns immediately.

4. Open a Shell as a Service Account That Uses /usr/sbin/nologin (-s)

Daemon accounts like www-data, nginx, or redis use /usr/sbin/nologin in /etc/passwd to block direct logins. Pass -s /bin/bash to test file permissions as that daemon.

sudo su -s /bin/bash - www-data -c "whoami && id && test -r /var/www/html/index.html && echo 'Readable OK'"

# Illustrative output (reviewed against documentation)
www-data
uid=33(www-data) gid=33(www-data) groups=33(www-data)
Readable OK

The -s /bin/bash option overrides /usr/sbin/nologin for this invocation (permitted because the caller is root), letting you verify whether www-data can traverse /var/www/html.

5. Preserve Selected Environment Variables Across a Login Switch (-w)

When using su - (--login), you can explicitly whitelist safe environment variables like DEPLOY_ENV or GIT_COMMIT so they survive the environment reset.

export DEPLOY_ENV="staging"
export SECRET_TOKEN="do-not-leak"
sudo su -w DEPLOY_ENV - alex -c 'echo "DEPLOY_ENV=$DEPLOY_ENV SECRET_TOKEN=${SECRET_TOKEN:-<cleared>}"'

# Illustrative output (reviewed against documentation)
DEPLOY_ENV=staging SECRET_TOKEN=<cleared>

-w DEPLOY_ENV preserves DEPLOY_ENV=staging while still scrubbing SECRET_TOKEN and resetting HOME, PATH, and USER.

6. Run su with Pseudo-Terminal Isolation (-P)

When switching from root to a less-trusted user account, allocate a dedicated pseudo-terminal (-P) so the child process cannot inject characters into the parent terminal.

sudo su -P -s /bin/bash - www-data -c "tty && id -un"

# Illustrative output (reviewed against documentation)
/dev/pts/3
www-data

-P (--pty) creates an isolated pseudo-terminal slave (/dev/pts/3) and proxies standard streams safely.

Real-World Workflows, Pipelines, and Shell Automation

Diagnose Permission Denied Errors for Systemd Service Accounts

When Nginx, PostgreSQL, or a custom systemd service fails with Permission denied on a TLS certificate or socket file, use su -s /bin/bash - <service_user> with namei -l to inspect every parent directory permission bit from the service account's perspective.

sudo su -P -s /bin/bash - www-data -c "namei -l /etc/ssl/private/app.key" || true

# Illustrative output (reviewed against documentation)
f: /etc/ssl/private/app.key
drwxr-xr-x root root     /
drwxr-xr-x root root     etc
drwxr-xr-x root root     ssl
drwx--x--- root ssl-cert private
app.key - Permission denied

Running namei -l as www-data immediately reveals why the file cannot be read: /etc/ssl/private has mode 0710 (root:ssl-cert), and www-data is not yet a member of ssl-cert.

Restrict 'su' to Members of the wheel/sudo Group via PAM

By default on many Linux distributions, any local user can run su - and attempt to guess the root password. Hardening /etc/pam.d/su by uncommenting pam_wheel.so restricts su execution strictly to members of the administrative group.

# Inspect active pam_wheel rules in /etc/pam.d/su:
grep -n "pam_wheel.so" /etc/pam.d/su

# To enforce restriction (on Debian/Ubuntu where admin group is 'sudo'):
# auth required pam_wheel.so use_uid group=sudo

# Illustrative output (reviewed against documentation)
15:# auth       required   pam_wheel.so

Enabling auth required pam_wheel.so use_uid group=sudo (or wheel on RHEL) causes PAM to immediately reject su calls from non-administrative accounts even if they know the target password.

Pipelines, Redirection, Quoting, and Shell Expansion

When embedding su inside shell pipelines (|), conditional chains (&& and ||), or command substitutions ($(...)), the calling shell performs tilde expansion, variable interpolation, and globbing before invoking the binary. Always wrap paths, patterns, and variables in quotes so whitespace and wildcard characters (*, ?) are not expanded prematurely, and use set -euo pipefail in unattended scripts.

Permissions, Security Implications, and Safe Execution

In multi-administrator environments, prefer sudo -i (or sudo -u username -i) over shared-password su -. With su -, every administrator must know the shared target password, revoking one engineer's access requires rotating the root password on every server, and system logs only show that someone authenticated to root. With sudo, engineers authenticate with their personal credentials, access is revoked per user, and every command is attributed to the original SUDO_USER in /var/log/auth.log.

Always pass -P (--pty) when running commands as an untrusted user from a privileged root shell so malicious code cannot abuse terminal ioctl calls.

GNU/Linux, BSD, and BusyBox Implementation Differences

Since util-linux 2.22, Linux distributions use the unified util-linux implementation of su supporting -l, -c, -s, -m, -w, and -P. Earlier Debian releases used the shadow package's su implementation, which omitted -P and -w.

On FreeBSD, OpenBSD, and macOS, su supports - (-l), -c, and -m, but the -s SHELL flag is not supported on BSD/macOS su (use sudo -u username /bin/bash instead). On Alpine Linux, BusyBox provides a minimal su applet unless util-linux-misc or shadow is installed.

Troubleshooting Common Errors and Diagnostics

su: Authentication failure (when switching to root on Ubuntu)

Root Cause: Ubuntu and most cloud Linux images lock the root account password by default (! in /etc/shadow), meaning no valid password exists for su -.

Resolution: Use sudo -i or sudo su - (which prompts for your personal user password instead of root's password).

sudo -i

This account is currently not available.

Root Cause: You tried to su - into a system or service account (such as www-data, nginx, or sshd) whose login shell in /etc/passwd is set to /usr/sbin/nologin.

Resolution: Explicitly override the shell using -s /bin/bash.

sudo su -s /bin/bash - www-data

su: cannot set groups: Operation not permitted

Root Cause: The /usr/bin/su binary lost its setuid root bit (04755), or the filesystem containing /usr is mounted with the nosuid mount option.

Resolution: Check ls -l /usr/bin/su and findmnt /usr, and restore the setuid bit (sudo chmod 4755 /usr/bin/su) if missing.

ls -l /usr/bin/su
sudo chmod 4755 /usr/bin/su

Authoritative References and Official Documentation

Frequently Asked Questions

Quick answers to common questions and configurations

4 FAQs
Running su without a hyphen switches the effective user ID but keeps your previous working directory and environment variables (like HOME and PATH). Running su - (or su -l) launches a completely clean login shell with the target user's environment, PATH, and home directory.
su switches to another user (defaulting to root) by requiring the TARGET user's password and starts a persistent shell. sudo executes a single command with elevated privileges by requiring YOUR OWN user password as authorized by /etc/sudoers.
Run sudo su -s /bin/bash - username. The -s flag overrides the nologin shell in /etc/passwd with /bin/bash for that session.
Ubuntu disables the root password by default for security. Instead of running su - directly, run sudo -i or sudo su - and enter your own sudo user password.
RR
Written byVerified Author

Rajesh Ray

I’m Rajesh Rai, a full-stack developer, Linux administrator, and technology enthusiast passionate about making complex technology easier to understand and use.

SPAM-FREE MODERATED DISCOURSE

Join the Conversation & Perspective

Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.

AT
MP
JV
+2

No comments on this guide yet. Be the first to share your thoughts or ask a question!

Recommended Reading10 Guides

Related Technical Guides

Tested runbooks, server administration walkthroughs, and troubleshooting guides

Featured Infrastructure PartnerUp to 75% OFF + 3 Months Free

Supercharge Your Linux & Cloud Workloads with Hostinger

Deploy high-speed NVMe KVM VPS, Docker containers, and LiteSpeed-accelerated WordPress servers in under 60 seconds with full root access, dedicated IPv4, and 24/7 technical support.

Pure NVMe SSD StorageFull Root Access & SSHFree Domain & Unlimited SSL99.9% Uptime SLA
Plans from$2.99/mo
Claim Hostinger DealAffiliate link • Special discount applied at checkout