As you have seen, it is a poor practice to log on to the server directly with root privileges. The better practice is to log on with a standard user account, then elevate your privileges to root as needed. One way of elevating privileges is to “substitute user” using the su command. The su command, without an option, enables a user to switch their identity to that of another user, but it retains the original user’s profile and variables. The switched user also remains in the home directory of the original user. Anyone using su except the root user will be challenged for the password of the user account they are switching to.
Using su with a hyphen following it enables a user to change users and launch a new shell under the context of that new user. This is a much better practice. Anyone using “su –”” except the root user will be challenged for the password of the user they are switching to. It is most common to switch to the root user, but any user can switch to any other user so long as they know the user’s password.
The syntax of the su command is:
$ su [-] [user name]
If you encounter below error while executing the su command:
su: command not found
you may try installing the util-linux package as shown below as per your choice of distribution.
Distribution | Command |
---|---|
OS X | brew install util-linux |
Debian | apt-get install util-linux |
Ubuntu | apt-get install util-linux |
Alpine | apk add util-linux |
Arch Linux | pacman -S util-linux |
Kali Linux | apt-get install util-linux |
CentOS | yum install util-linux |
Fedora | dnf install util-linux |
Raspbian | apt-get install login |
su Command Examples
1. Switch to superuser (requires the root password):
$ su
2. Switch to a given user (requires the user’s password):
$ su username
3. Switch to a given user and simulate a full login shell:
$ su - username
4. Execute a command as another user:
$ su - username -c "command"
Note
One option is permitted when executing the su command: the – option. When you execute the su command with the – option, a new login shell will be provided. When not using the – character, a non-login shell will be provided.