Linux su Command: Switch User Accounts and Login Shells

su is a tool used to run a shell or commands with an alternative user and group ID. If no user is specified, it typically targets root, and using su --login user switches to an environment similar to that of directly logging in as that user.

A simple su user keeps the current working directory and some of the environment, which can mix with the settings of another user. For an interactive account switch, su --login user is usually used, and if the purpose is just to run a single administrative command, it is better to first consider whether policy-based sudo is more appropriate.

What is the su command?

su stands for substitute user and group ID, and executes commands using an alternative user and group ID. Omitting the username attempts to start an interactive shell as the root account.

The su from util-linux performs authentication, and account and session management through PAM (Pluggable Authentication Modules). Which password is required, whether only certain groups can use su, and where attempts are logged can vary depending on the distribution's PAM and security settings.

This article is based on the util-linux implementation, which is widely used in Linux. The exact behavior and system-specific configuration files can be found on the official util-linux su manual page.

Basic Syntax and Account Switching

The basic syntax is as follows.

su [options] [-] [user [arguments...]]

If no user is specified, it attempts to switch to the root account.

su

When executed by a regular user, it usually prompts for the password of the target root account. If the root account is locked or PAM policy does not allow it, the switch cannot be made even if the correct user password is known.

To switch to a specific user, specify the account name.

su deploy

To return to the original shell, run exit in the switched shell or press Ctrl+D.

exit

The difference between su and su --login

Category su user su --login user
working directory keep current directory move to the target user's home directory
environment variables only partially changed and may mix with the existing environment mostly cleared to set up the target user's login environment
PATH Affected by system settings and PAM Initialize to match the target login environment
Shell startup method Standard interactive shell Start as a login shell
Recommended situations Intended for limited cases where environment retention is desired Normal interactive user switching

The util-linux manual recommends using --login to avoid side effects from mixed environments. The short form - has the same meaning.

su --login deploy
su - deploy

Changes in the login shell environment

Cleans up most of the existing environment variables

The su --login of util-linux clears the existing environment except for TERM, COLORTERM, NO_COLOR, and explicitly allowed variables. It then initializes HOME, SHELL, USER, LOGNAME, and PATH based on the target user.

The final environment may also reflect values added or modified by PAM modules, so it should not be assumed to be exactly the same across distributions.

Move to the target user's home directory

--login starts the login shell after moving to the target user's home directory. After switching, you can check the user, home, and working directory with the following commands.

id
printf '%s\n' "$HOME"
pwd

Shell initialization files change

The login shell reads initialization files for login according to the rules of the shell used. For Bash, it may be influenced by system and user settings such as /etc/profile and ~/.bash_profile. Check the manual of the target shell and the account settings for the actual order.

Frequently used su options

Option Function Usage and precautions
-, -l, --login Switch to login shell environment Generally recommended for interactive switching
-c command, --command command Pass a single command to the shell Must check quoting and exit status
-s shell, --shell shell Specify the shell to execute In a restricted shell account, it may be ignored if the caller is not root
-m, -p, --preserve-environment Preserve the current environment as much as possible Ignored when used with --login, use cautiously for security
-w list, --whitelist-environment list Preserve specified environment variables when switching login Separated by commas, excluding core account variables
-P, --pty Create a separate pseudo terminal in the session Useful for terminal splitting in interactive sessions
-g group Specify default group Only root user can use
-G group Specify secondary group Only root user can use and repeatable

Execute a single command as another user

Execute one command with -c

If you don’t need to stay in an interactive shell, you can pass commands to the target user’s shell with -c.

su -c 'id' deploy

When the command ends, su also terminates and returns to the original shell. Since the command string is reinterpreted by the target shell, be careful with quotes, variable expansion, and the timing of redirection.

Executing commands in a login environment

To run commands in the target user’s login environment and home directory, use --login together.

su --login -c 'pwd; id' deploy

Both commands connected with a semicolon are executed inside the target user’s shell. Do not pass dynamically created strings with elevated privileges directly if they include external input, as this risks command injection.

Checking the exit status of commands

su generally returns the exit status of the executed command. In the util-linux implementation, it returns 126 if the command cannot be executed, 127 if the command is not found, and 1 for general errors before command execution.

su -c '/usr/local/bin/check-job' deploy
status=$?
printf 'exit=%s\n' "$status"

In automation, you should check not only the output string but also the exit status.

Handling Shells and Restricted Accounts

Default Shell of the Target User

Unless specified otherwise, the shell set in the target account's passwd entry is generally used, and if absent, it defaults to /bin/sh. When checking account information, do not arbitrarily modify the entire /etc/passwd; instead, query it as follows.

getent passwd deploy

Specifying Shell with -s

You can specify a different shell with -s.

su -s /bin/sh -c 'id' deploy

If the target account's shell is a restricted shell not listed in /etc/shells, the shell specified by a regular user may be ignored. Just because root can bypass the restriction does not mean it is safe to open an interactive shell for a service account.

Respecting the Purpose of Service Accounts

Accounts with nologin or false set as their shell are likely not intended for interactive logins. If you need to work with such an account, run only the necessary command and first check whether there are management commands provided by the service or if systemd features are available.

Use environment variable preservation carefully

Meaning of --preserve-environment

The --preserve-environment option preserves the current environment without resetting HOME, SHELL, USER, or LOGNAME. It is ignored if specified with --login.

su --preserve-environment deploy

Unless it is a special case where the calling user's settings must be passed as-is, mixing the target account's home and execution environment can lead to unexpected file ownership or configuration changes.

Allow only necessary variables

In util-linux, you can preserve only the necessary variables by combining --login and --whitelist-environment.

su --login --whitelist-environment=LANG,LC_ALL deploy

HOME, SHELL, USER, LOGNAME, and PATH are excluded from the whitelist. Locale variables can also affect program behavior, so only pass values that are absolutely necessary.

Difference between su and sudo

Category su sudo
Main Purpose Execute shell or commands as another user Execute commands as another user permitted by policy
General Authentication Target user's password Calling user's password
Scope of Privileges Continue using the target account's privileges in the switched shell Can be restricted with allowed commands and conditions
Audit and tracking Focused on session switching records, and internal command tracking requires separate tracking Execution requests can be recorded through policy/logging plugins
Suitable situations If the target account requires an interactive environment Execute a single administrative command or minimum privileges per role

Authentication method and logging may vary according to PAM and policy, so the above table is a general comparison. If only a root command is needed, sudo, which can limit privileges per command, is often more suitable than su, which shares the account password. For detailed usage, refer to Linux sudo command and sudoers configuration.

Reason for not switching to the root account

The root account may be locked

Some distributions disable password login for the root account by default and use administration through sudo. In this case, entering the current user's password in su - will not succeed.

If the user has sudo privileges and the policy allows it, a login-style root shell can be opened as follows, but if only individual commands are needed, it is safer to use sudo command rather than an administrator shell.

sudo -i

PAM or group policies may impose restrictions

The policy in /etc/pam.d/su can restrict the use of su to specific groups or enforce additional authentication requirements. Do not arbitrarily weaken PAM settings to gain privileges; instead, provide the system administrator with the necessary tasks and target accounts.

There may be issues with the target account status

Switching may fail due to account expiration, locking, incorrect home directory, restricted shell, or file permissions. If you are an administrator, check the cause with getent passwd user, account management tools, and authentication logs.

When root runs as another user

runuser may be more suitable for automation

The util-linux manual already recommends runuser when running as another user from a process with high privileges or root's scripts. runuser is not set-user-ID, does not require password authentication, and uses a separate PAM configuration.

runuser -u backup -- /usr/local/bin/backup-job

runuser is an administrative tool used by root, so it is not a command for a regular user to gain privileges instead of sudo.

If a PAM session is not needed, reconsider the purpose

If you simply need to change user/group IDs and permission attributes to run a program and a PAM session is not required, util-linux also suggests setpriv as an alternative. This tool directly manages privileges and security attributes, so it should only be used by administrators who understand the exact user, group, supplementary group, and capability settings.

Separate the session with a pseudo terminal

Separation provided by --pty

--pty creates a separate pseudo terminal between the original session and the target session, and su relays the input and output. This can improve security by preventing the two sessions from directly sharing the same terminal in an interactive session.

su --pty --login deploy

Not a full systemd login session

Even when using su --login, it does not create a completely new actual login session from the perspective of systemd-logind. If you need tasks that require user services, seats, or session boundaries, you should consider tools suited for the purpose, such as systemd-run or machinectl.

Security precautions

  • Do not share the root password or other users' passwords with multiple people.
  • Do not put passwords on the command line, shell history, scripts, or pipes.
  • Do not keep a root shell open longer than necessary; exit immediately after completing work.
  • Immediately after switching, check id, pwd, and HOME to avoid confusion between users and paths.
  • For commands to be run with elevated privileges, first review the options, target paths, and results of wildcard expansions.
  • Do not assume that logs are retained; instead, check the actual settings and retention policies of PAM, journal, and authentication logs.

Commands executed after opening a root shell with su are separate from the authentication records of su itself. If individual command auditing is required, you should design it alongside shell auditing, centralized logging, or methods like sudo that provide per-command policies.

Common problems and solutions

Symptoms Possible cause How to check
Authentication failure Target password errors, account lockout, or PAM restrictions Check the target account and authentication policy/logs
Cannot find the command after switching The target user's PATH is different Check command -v and printf '%s\n' "$PATH"
Home directory does not change Use su user without login option Use su --login user
User settings appear to be mixed Use regular su that partially retains the existing environment Check env, HOME, USER
The specified shell does not run Restricted shell or call permission restriction Check getent passwd and /etc/shells

Frequently Asked Questions

Whose password do you enter for su?

Generally, you enter the password of the target user you want to switch to. However, if root executes it or PAM policies use different authentication methods, the behavior may vary. It is normal that characters are not displayed on the screen while entering the password.

What is the difference between su and su -?

su runs a root shell while maintaining the current directory and part of the environment. su - moves to the root's home and sets up the login environment. In util-linux, the login form is recommended to reduce environment mixing.

How do you check the current user after switching with su?

id is useful for checking both real and effective users and groups together. If you only need a simple username, you can use whoami, but to check supplementary groups, id provides more information.

Is it okay to put the su password in the script?

No. The password can be exposed in files, process information, or logs. If automating as root, design a method using a limited runuser. If it's for privilege escalation as a regular user, design a way that does not embed the password, such as using minimal privilege sudoers rules or a dedicated service for the task.

Summary

For general interactive account switching, you can use su --login user, and for a single command, su -c 'command' user. A simple su user may mix environments, so it is good to check id, HOME, and pwd after switching.

If the goal is to execute just one root command, sudo, which provides per-command permission control and auditing, may be more appropriate. When running as another user in root automation, consider runuser. You can also check related basic tools together in the list of commonly used commands in Linux.

More in This Category
Linux uniq Command: Remove or Count Adjacent Duplicate Lines

Linux uniq Command: Remove or Count Adjacent Duplicate Lines

Learn how to remove or count adjacent duplicate lines with the Linux uniq command, including practical examples, key options, and important precautions.

Linux free Command: Check Memory and Swap Usage

Linux free Command: Check Memory and Swap Usage

Learn how to use the Linux free command to inspect available memory, used memory, cache, and swap usage, with essential options, practical examples, output interpretation, and common troubleshooting tips.

Linux systemctl Command: Manage systemd Services

Linux systemctl Command: Manage systemd Services

Learn how to manage systemd Services with the Linux systemctl command, including practical examples, key options, and important precautions.

Linux Tutorial / Understand systemd Services, Boot, and Logs

Linux Tutorial / Understand systemd Services, Boot, and Logs

Understand Linux boot stages and systemd units, distinguish active services from boot enablement, and inspect current-boot logs with systemctl and journalctl.

Linux bg Command: Resume a Shell Job in the Background

Linux bg Command: Resume a Shell Job in the Background

Learn how to resume a Shell Job in the Background with the Linux bg command, including practical examples, key options, and important precautions.

Best Linux Distributions for Web Servers: Ubuntu, Debian, or Rocky Linux?

Best Linux Distributions for Web Servers: Ubuntu, Debian, or Rocky Linux?

Compare Ubuntu Server, Debian, and Rocky Linux for web hosting based on support lifecycle, package freshness, documentation, operational stability, and application requirements.

Linux fsck Command: Check and Repair Filesystems

Linux fsck Command: Check and Repair Filesystems

Learn how to check and Repair Filesystems with the Linux fsck command, including practical examples, key options, and important precautions.

Linux printenv Command: Print Environment Variable Values

Linux printenv Command: Print Environment Variable Values

Learn how to use the Linux printenv command to print all environment variables or selected variable values, with essential options, practical examples, output interpretation, and common troubleshooting tips.

Linux nslookup Command: Query DNS Names and Records

Linux nslookup Command: Query DNS Names and Records

Learn how to query DNS Names and Records with the Linux nslookup command, including practical examples, key options, and important precautions.

Bash Command Operators Explained: ;, &&, ||, &, and |

Bash Command Operators Explained: ;, &&, ||, &, and |

Understand how Bash operators run commands sequentially, conditionally, in the background, or through pipelines, with practical examples and precedence guidance.