How to Switch Users in Linux
As with any operating system, Linux can have multiple user accounts. Sometimes we may need to use other user accounts to access files or be root to run a command that requires privileges.
This article will explain how to switch between different users.
Use the su
Command to Switch Users in Linux
The su
command allows you to log into a different user account whose password you know. If used without parameters, the root user is selected by default. You can use the whoami
command to view the current user.
To switch to a specific user account, type the username after the command. Use the -
(or -l
, --login
) parameter to clear the current user’s environment variables and log in with the new user’s variables.
su - user
Output:
Use the -c
or --command
parameter to run commands with a different user account.
su --command=whoami - user
Output:
Use the -s
or --shell
parameter to switch with a different shell than the current one.
su --shell=/bin/sh - user
Output:
Use sudo
to Run Commands as Root in Linux
The sudo
command allows executing commands with the permissions of a different user, usually superuser, rather than switching the current user account.
For example, the only root user can update packages installed on the system. The apt-get update
command updates the Ubuntu operating system.
If you are not the root user, this command gives an error. You have to use the command as follows.
sudo apt-get update
Output:
Using the sudo
command instead of switching to the root account with the su
command is safer.
This way, the permissions will only apply to the apt-get update
command. Thus, situations such as unconscious users forgetting to log out of the root account and using harmful commands are prevented.
Yahya Irmak has experience in full stack technologies such as Java, Spring Boot, JavaScript, CSS, HTML.
LinkedIn