Before you start
Objectives: Learn what is root account, how should it be used, and how to change to it to execute commands.
Prerequisites: no prerequisites.
Key terms: root, administrator, Linux, system, su command. su –
root User
The root user account on Linux system is created during the installation process and is a superuser which can perform any task on the system. Because of this fact, we have to make sure that the root user account information (password) is protected.
Recommended way of doing things on Linux system is to create a user account that gives us sufficient permissions to perform most of our daily work. We should use this account instead of the root user account when logging in to the system. When we have to perform tasks that require the root user account, we can use the su command to switch to the root user and execute the command. When we’re finished executing commands, we can use the exit command to revert to our regular account. For example, to log in to the root account we would enter the command:
su -l root
The same thing is accomplished using the following two commands:
su - root
su -
If we don’t specify the name of the user account, the su will assume the root user account. The options “-l” or “-” mean that we want to make this a login shell. This means that our environment variables and home directory will change to the one of the user we are logging as. Look at the example below in which we first don’t use the “-” option, and then we use it. Note how the home directory changes.
su command with and without “-” option
If we only want to execute a single command with root privileges, and then go right back to our regular user account we can use the “-c” option.
su -c 'command' -l name
For example, to read the sudoers file using less, we would enter the following:
su -c 'less /etc/sudoers' -l root
So, with su -c we switch to the root user and execute the command. We can enclose the command in either single or double quotation marks.
To show the current user’s login name we can use the following command:
whoami
To show all users logged in to the system we can use the command:
who -u
Sudoers
You can also give individual users or groups the ability to execute commands as the superuser by using the sudo command. Users and the commands they are entitled to execute are stored in the/etc/sudoers file. To give a user the ability to execute a command, we can create an entry in the/etc/sudoers file.
When users need to execute the command, they use the sudo command followed by the command they want to execute. Users will be prompted for a password before the command will execute. This is the current user account password, not the root account password. sudo logs information about the users and the commands they run (or try to run).
We have a another article in which we explain the /etc/sudoers in more detail.