Linux su command

Linux 命令大全Linux Command Collection

The Linux su (full English name: switch user) command is used to switch user identity. Except for root, you need to enter the password of that user.

Permissions: all users.

Syntax

su [选项] [用户名]

For example:

su              # 切换到root,保持当前环境
su -            # 切换到root,加载root的完整环境
su root         # 明确指定切换到root用户

Switch to another user:

su username
su - username
su -l username

Parameter description:

  • -or-lor--login: Provide an environment similar to direct login
  • -c command: Execute the specified command and then exit
  • -s shell: Specify the shell to use
  • -por--preserve-environment: Preserve current environment variables

Examples

Temporarily execute a command as root:

su -c "apt update && apt upgrade" root

Switch to a service user for debugging:

su - www-data
su -s /bin/bash www-data  # 如果默认shell是/bin/false

Use in scripts:

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

Exit su session:

exit        # 退出当前su会话
Ctrl+D      # 同样可以退出

Difference between su and su -

su(Non-login switch):

  • Keeps the current user's environment variables
  • Working directory unchanged
  • Environment variables such as PATH remain unchanged

su -(Login switch):

  • Loads the target user's complete environment
  • Switches to the target user's home directory
  • Resets environment variables such as PATH and HOME
  • Executes the target user's login scripts

Example comparison

# 当前用户:john,工作目录:/home/john
pwd                    # /home/john
echo $HOME            # /home/john

su root
pwd                   # /home/john (目录未变)
echo $HOME           # /home/john (环境未变)
exit

su - root
pwd                  # /root (切换到root家目录)
echo $HOME          # /root (完整环境)
exit

Difference between su vs sudo

Feature su sudo
Password required Target user's password Current user's password
Session duration Until manual exit Single command or short-term caching
Configuration complexity Simple Requires configuring sudoers
Security Need to know the root password More fine-grained permission control
Audit Limited More detailed logs

Although the su command is simple and direct, sudo is usually the more recommended choice in modern system administration because it provides better security and auditing capabilities.


Security considerations

  • Avoid sharing the root password
  • Usesu -Ensure complete environment switching
  • Exit su sessions promptly
  • Prioritize the use of sudo in production environments
  • Monitor su usage logs (usually in /var/log/auth.log)

Linux 命令大全Linux Command Collection

Other extensions