The su
command allows you to change to a specific user in Linux. Let's see some use cases you might need in the section below.
Change to Another User with su Command
To change to another user in Linux, type in su
followed by the username of the user you want to switch to.
su <username>
For example, to switch to the user named "dminhvu" (which is my username), you would run:
su dminhvu
Enter the password of that user as it says, then you will be logged in as the user "dminhvu".
Change to Root User
To switch to the root user in Linux, you can simply run the su
command without specifying a username:
su
You will be prompted to enter the root password. After entering the password, you will be logged in as the root user.
Run Command as Another User without Switching
You may want to run a command as a different user without switching to that user's shell. You can achieve this using the sudo
command with the -u
option, followed by the username.
For instance, to run the ls
command as the user "dminhvu", you can run:
sudo -u dminhvu ls
You will be prompted to enter your own password, and the ls
command will be executed as the "minhvu" user.
Create a New User in Linux
In case you do not have a user account yet, you can create a new user in Linux using the adduser
command.
adduser <username>
For example, to create a new user named "dminhvu", you would run:
adduser dminhvu
Enter your password if prompted. Then you will be asked to enter some information about the user. You can leave them blank by pressing Enter to use the default values.
Adding user 'dminhvu' ... Adding new group 'dminhvu' (1001) ... Adding new user 'dminhvu' (1001) with group 'dminhvu' ... Creating home directory '/home/dminhvu' ... Copying files from '/etc/skel' ... New password: Retype new password: passwd: password updated successfully Changing the user information for dminhvu Enter the new value, or press ENTER for the default Full Name []: Minh Vu Room Number []: Work Phone []: Home Phone []: Other []: Is the information correct? [Y/n]
Conclusion
That's all. Good luck!