The Linux terminal is packed with useful command, but none of them is as important as the sudo command. It lets you run commands as any other user, with the root user being the default.
In this article, we’re going over the sudo command, how it works, and when you can use the command to your advantage.
Also read: How to rename a file in Linux?
While the sudo package is pre-installed on most Linux distros, if you get a sudo command not found error, you can install it using a simple command.
- Ubuntu and Debian: apt install sudo
- CentOS and Fedora: yum install sudo
To use the sudo command, you’re going to have to add the required user to the sudoers group. The command reads the /etc/sudoers file to check whether or not the invoking user is granted with sudo access. If it’s the first time you’re using the command in a session, you’ll be asked for your password as well.
Also read: How to check the list of users in Linux?
Using the sudo command
The basic syntax for the sudo command is as follows.
sudo -flag command
Note that there are many flags you can use with sudo to alter its behaviour, but it’s most often used in its most basic form.
By default, the command will ask you to enter your password again after five minutes of sudo inactivity. If you want to change this timeout, follow these steps to edit the sudoers file.
Step 1; Type the following command to edit the sudoers file.
Step 2: Add the line below and change the number to whatever you want the timeout to be in minutes
If you’re looking to change the timeout for a particular user, use the following syntax.
Also read: How to change password in Linux?
Run a command as a user other than root
Sudo can not only run commands as the root user, but it can also be used to run commands like any other user that you’d want using the -u option.
sudo -u eculid whoami
Also read: Linux Chown command explained
How to redirect commands with sudo
Using sudo, you can try to redirect the output of a command to a file. However, if you’re trying to run the command without the write permissions for that file, you’ll get a ‘permission denied’ error.
sudo echo "test" > /root/file.txt
This happens because the redirection of the output is performed through the user you’re running the command and not the sudo command.
One solution to this is to invoke a new shell as root using this command.
sudo sh -c
So the redirection command will look something like this.
sudo sh -c 'echo "test" > /root/file.txt'
The second alternative is to pipe the command’s output as a regular user to the tee command.
echo "test" | sudo tee /root/file.txt
Also read: How to shutdown Linux from Command Line?
Someone who writes/edits/shoots/hosts all things tech and when he’s not, streams himself racing virtual cars. You can reach out to Yadullah at [email protected], or follow him on Instagram or Twitter.