su (Switch User)
The su
command is used to switch to another user temporarily. You can also switch to the superuser. Switching to the superuser is useful especially when you set up a new server which requires several new settings such as adding new users, passwords, groups, and several other system configurations.
Switch to another normal user : su [user name]
When you specify the username when you run the command, you can switch to the user. You need to add a user before switching to the user, which will be explained later.
Switch to the superuser : sudo su
When you run the su
command without any username, you can switch to the superuser. As the normal user usually doesn't have the privilege to switch to the superuser, you need to add the "sudo
" prefix when you run the su
command.
Change user environment : " - " option
By adding the " -
" option, you can also change the user environment. For example, when you switch to the superuser with the " -
" option, your command line's current working directory changes to /root
(root user's home directory).
Switch back to the original user : exit
To switch back to the original user, you can run the exit
command. If you run the su
command multiple times, you need to run the exit
command the same number of times to go back to the original user.
Practice
1. sudo su (without the - option)
To clearly see how the command works, create a new directory dir_1, and go to the directory first.
cd ~
mkdir dir_a
cd dir_a
To switch to the superuser account, run the sudo su
command (without the -
option).
sudo su
You can see that the username changed to root
and $
changed to #
. Also, you can see that the displayed path of the current directory shown before #
has changed although the current directory position hasn't. This is because your home directory has changed.
To check the status, go to the home directory by running the cd ~
command.
cd ~
Check the current working directory with the pwd
command. You can see that the home directory becomes /root
(but not on ubuntu
anymore).
pwd
/root
2. sudo su -
First, exit from the sudo status by running the exit command. You'll see that the user has switched back to ubuntu
and the current working directory has moved back to its original position.
exit
Run the sudo su
command with the -
option. You can see that the user has switched to root
and the current working directory has changed to the new home directory.
sudo su -
Run the pwd
command. You can confirm that the home directory has changed to /root
.
pwd
/root