Linux Comm Su
# Linux su Command
[ Linux Command Manual](#)
The Linux su (short for switch user) command is used to switch user identity. Except for root, you need to enter the user's password.
Usage permissions: All users.
### Syntax
su
For example:
su # Switch to root, keep current environment su - # Switch to root, load root's full environment su root # Explicitly specify switching to root user
Switch to other users:
su username su - username su -l username
**Parameter Description**:
* `-` or `-l` or `--login`: Provides an environment similar to a direct login
* `-c command`: Executes the specified command and then exits
* `-s shell`: Specifies the shell to use
* `-p` or `--preserve-environment`: Preserves current environment variables
### Examples
Temporarily execute commands 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 # If the default shell is /bin/false
Use in scripts:
su - postgres -c "psql -c 'SELECT version();'"
Exit su session:
exit # Exit current su sessionCtrl+D # Also can exit
* * *
## Difference between su and su -
**`su` (non-login switch):**
* Keeps current user's environment variables
* Working directory remains unchanged
* PATH and other environment variables remain unchanged
**`su -` (login switch):**
* Loads the target user's full environment
* Switches to the target user's home directory
* Resets PATH, HOME, and other environment variables
* Executes the target user's login scripts
### Example Comparison
# Current user: john, working directory: /home/john pwd # /home/john echo $HOME # /home/john su root pwd # /home/john (directory unchanged) echo $HOME # /home/john (environment unchanged)exit su - root pwd # /root (switched to root's home directory) echo $HOME # /root (full environment)exit
* * *
## Difference between su vs sudo
| Feature | su | sudo |
| --- | --- | --- |
| Requires Password | Target user's password | Current user's password |
| Session Duration | Until manual exit | Single command or short-time cache |
| Configuration Complexity | Simple | Requires sudoers configuration |
| Security | Requires knowing root password | More granular permission control |
| Audit | 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 provides better security and auditing capabilities.
* * *
## Security Precautions
* Avoid sharing the root password
* Use `su -` to ensure a complete environment switch
* Exit su sessions promptly
* Prefer using sudo in production environments
* Monitor su usage logs (usually in /var/log/auth.log)
[ Linux Command Manual](#)
YouTip