su Command in Linux
Overview
The su command, short for 'substitute user' or 'switch user', is a Linux command that allows you to execute commands with the privileges of another user. It is commonly used to switch to the root user, granting access to administrative commands and functions.
Linux su Command Syntax
The syntax for the su command is as follows:
Where:
- options: The options allow you to modify the behavior of the su command.
- username: The username of the user you want to switch to. If not provided, it defaults to the root user.
su Command Options:
- -c: Execute a single command as the specified user and exit.
- -l: Simulate a full login by the specified user, setting environment variables and changing the working directory to the user's home directory.
- -p: Preserve the current environment variables when switching users.
- -s: Specify the shell used to execute commands, overriding the default shell for the specified user.
Example Usages
-
Switch to the root user:
Output:
Explanation: This command switches to the root user, prompting for the root password. After successful authentication, the command prompt changes to the root user's prompt.
-
Switch to a different user:
Output:
Explanation: This command switches to the user 'john', simulating a full login by setting environment variables and changing the working directory to John's home directory.
Tips
- Always use 'su' with caution, especially when switching to the root user, as it grants access to administrative commands that can potentially harm your system.
Advanced Use Cases of su Command in Linux
-
Execute a single command as another user:
Output:
Explanation: This command executes the 'cat /etc/shadow' command as the root user, displaying the contents of the /etc/shadow file, which is normally not accessible by regular users.
-
Switch to a different user and use a custom shell:
Output:
Explanation: This command switches to the user 'john' and starts the tcsh shell, overriding the default shell for that user.
Conclusion
-
The su command is used to switch to another user, granting access to their permissions and privileges.
-
It can be used to execute a single command as another user or to simulate a full login.
-
Always use 'su' with caution, especially when working as the root user.