0
0
Linux CLIscripting~5 mins

su (switch user) in Linux CLI - Commands & Configuration

Choose your learning style9 modes available
Introduction
Sometimes you need to do tasks as another user on your Linux system. The su command lets you switch to a different user account temporarily without logging out.
When you need to install software as the root user but are logged in as a regular user.
When you want to test commands or scripts as another user without logging out.
When you need to access files or settings that only another user can access.
When you want to switch to a less privileged user for safer testing.
When you want to run a command as another user without opening a new session.
Commands
Switch to the root user with a login shell, which loads root's environment variables and settings.
Terminal
su -
Expected OutputExpected
Password: root@hostname:~#
- - Starts a login shell for the target user, loading their environment.
Switch to user 'alice' with a login shell to use her environment and permissions.
Terminal
su - alice
Expected OutputExpected
Password: alice@hostname:~$
- - Starts a login shell for the specified user.
Run the command 'whoami' as user 'alice' without switching to an interactive shell.
Terminal
su -c "whoami" alice
Expected OutputExpected
alice
-c - Runs a single command as the specified user.
Exit from the switched user session and return to your original user.
Terminal
exit
Expected OutputExpected
user@hostname:~$
Key Concept

If you remember nothing else from this pattern, remember: su lets you temporarily become another user to run commands or access files with their permissions.

Common Mistakes
Running 'su' without specifying '-' or '-l' and expecting the full environment of the target user.
Without '-', su keeps your current environment, which can cause unexpected behavior or permission issues.
Always use 'su -' or 'su -l' to switch to a full login shell of the target user.
Trying to switch to root without knowing the root password.
su requires the target user's password, so without root's password you cannot switch to root.
Use 'sudo' if you have sudo privileges or ask the administrator for the root password.
Not exiting the su session and getting confused about which user you are logged in as.
You might run commands with unintended permissions, risking system changes or security issues.
Use 'exit' to return to your original user when done.
Summary
Use 'su -' to switch to root with a full login environment.
Use 'su - username' to switch to another user with their environment.
Use 'su -c "command" username' to run a single command as another user.
Use 'exit' to return to your original user after switching.