Linux su command
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:
-or-lor--login: provides an environment similar to a direct login-c command: execute the specified command and then exit-s shell: specify the shell to use-por--preserve-environment: preserve the current environment variables
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):
- Keeps the current user's environment variables
- The working directory does not change
- Environment variables such as PATH do not change
su -(login switch):
- Loads the target user's full 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
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
- Avoid sharing the root password
- Use
su -Ensure a complete environment switch - Exit the su session promptly
- Prefer using sudo in production environments
- Monitor su usage logs (usually in /var/log/auth.log)
Linux Command Reference