Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Linux su command

Linux su command

Linux Command Reference Linux Command Reference

The Linux su (full English spelling: switch user) command is used to switch user identity; except for root, you need to enter that user's password.

Permissions required: 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:

Example

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 a script:

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

Exit the su session:

exit        # 退出当前su会话

Ctrl+D      # 同样可以退出


The difference between su and su -

su(non-login switch):

su -(login switch):

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


The difference between su and sudo

Feature su sudo
Password required Target user's password Current user's password
Session duration Until manually exiting with exit A single command or a short cached period
Configuration complexity Simple Need to configure sudoers
Safety Need to know the root password More fine-grained permission control
Auditing Limited More detailed logs

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


Security considerations

Linux Command Reference Linux Command Reference