How to Use the sudo Command in Linux [15 Practical Examples]

Try this guide with our instant dedicated server for as low as 40 Euros

sudo Command

Linux, a very capable operating system for server operations, offers extensive control over system operations.

Ask any Linux user, and they’ll tell you that the sudo command is a crucial tool in managing their systems. Standing for “superuser do,” this command allows users to execute commands with administrative privileges. Generally, it is used to execute commands for system management and security.

In this comprehensive tutorial, we’ll show you how to use the sudo command in Linux systems. We’ll start with how to use this command in several Linux distributions. We’ll round off with fifteen use cases where you can use sudo to optimize your system administration experience.

Table Of Contents

  1. Prerequisites
  2. How to Use the sudo Command in Linux?
    1. Syntax
  3. Granting sudo Privileges
    1. RedHat and CentOS
    2. Debian and Ubuntu
  4. How to Use the sudo Command in Linux: Practical Examples
    1. Example #1: Update System Packages
    2. Example #2: Run a Script as Another User
    3. Example #3: Start a Root Shell Session
    4. Example #4: Rerun the Last Command with Elevated Privileges
    5. Example #5: Execute a Sequence of Commands
    6. Example #6: Append Text to a Protected File
    7. Example #7: Restart a Service
    8. Example #8: Install a Package on a System
    9. Example #9: Edit a System Configuration File
    10. Example #10: View Protected Log Files
    11. Example #11: Add a New User Account
    12. Example #12: Change File Owners
    13. Example #13: Change Hostname
    14. Example #14: List Disk Usage
    15. Example #15: Kill a Process
  5. Conclusion
  6. FAQ

Prerequisites

Before delving into sudo, ensure you have:

How to Use the sudo Command in Linux?

Let’s start with an overview of the command:

Syntax

The basic syntax of the sudo command is:

sudo [OPTION] COMMAND

This syntax allows you to run the COMMAND as a superuser or another user on the command prompt.

The Command Flags

The robustness of the sudo command comes from the flags that extend the capabilities of the base command. Some of these flags are:

  • -u [user]: Execute as a specified user.
  • -l: List allowed (and forbidden) commands for the current user.
  • -v: Extend sudo timeout for another 15 minutes.
  • -h: Excellent resource for troubleshooting or for understanding more about what each option in sudo does.

sudo -h

Granting sudo Privileges

Granting sudo privileges to users is an important aspect of managing a Linux system. Users with this privilege level can perform tasks that require administrative or superuser permissions.

We strongly recommend caution when assigning these privileges to users because of the potential for system-wide changes.

Here’s how you can do it on different Linux distributions

RedHat and CentOS

For RedHat and CentOS, add users to the wheel group to grant them sudo privileges:

# usermod -aG wheel username

Debian and Ubuntu

In Debian and Ubuntu, users are added to the sudo group:

# adduser username sudo

adduser ameya user

Note: To perform these actions, you might need to log in with an administrator account or utilize the su command to switch to a user with the necessary permissions.

Using visudo and the sudoers Group

The sudoers file is the core configuration file for sudo, mainly in Debian-based distributions. It determines who can run what commands as which users on which machines. This file is typically located at /etc/sudoers.

visudo is a utility for safely editing the sudoers file.

It uses the system’s default editor, often Vi or Vim. You can set a different editor by exporting the EDITOR environment variable. For instance, use this statement to set nano as your default system editor.

export EDITOR=nano

During the edit process, visudo locks the sudoers file, preventing simultaneous edits that could lead to corruption or misconfiguration by multiple users. It also performs syntax checking to avoid errors because of improperly formatted statements.

sudoers Syntax and Structure

The sudoers file contains entries defining which users or groups have sudo privileges. Each entry typically follows this format:

user HOST = (USER:GROUP) COMMANDS

You can define aliases for users, hosts, and commands to simplify and organize entries. Here are two examples of how you can define these aliases:

  • User_Alias ADMINS = alice, bob
  • Cmnd_Alias UPDATE = /usr/bin/apt update, /usr/bin/apt upgrade

Add a line to the sudoers file in the following format to grant a user basic sudo privileges:

ameya ALL=(ALL:ALL) ALL

Even when assigned the basic sudo privileges, the user must still enter a password when executing a command. If you want a user to sidestep this process, add the following statement:

ameya ALL=(ALL:ALL) NOPASSWD: ALL

harmless preservation of user

The sudo privileges are usually assigned through groups for easier management. For instance, on Ubuntu, users in the sudo group have administrative privileges. The following statement means all users in the sudo group can execute any command on any host as any user:

%sudo ALL=(ALL:ALL) ALL

Best Practices

When working with the sudoers file, we recommend the following best practices:

  • Limit Access: Only grant permissions that are absolutely necessary.
  • Use Aliases: For complex configurations, use aliases to keep the sudoers file manageable and readable.
  • Regular Review: Periodically review the sudoers file for any necessary updates or security improvements.

How to Use the sudo Command in Linux: Practical Examples

Example #1: Update System Packages

To update all installed packages, run the following command:

# sudo apt-get update && sudo apt-get upgrade

This is a common operation in the Debian-based distribution like Ubuntu.

sudo su ameya

Example #2: Run a Script as Another User

Execute a script from the user ameya’s account:

# sudo -u ameya /path/to/script.sh

Example #3: Start a Root Shell Session

Start a new root access session:

# sudo -s

This opens a new shell session as the root user.

sudo -s

Example #4: Rerun the Last Command with Elevated Privileges

If you forgot to add sudo to a command (and the command didn’t run as expected), simply run the following command to execute the last entered shell command with sudo:

# sudo !!

sudo sudo su ameya

Example #5: Execute a Sequence of Commands

If you need to run multiple commands that require sudo privileges, use the following syntax:

# sudo sh -c 'command1 && command2 && command3'

Example #6: Append Text to a Protected File

Use the echo command with sudo to add text to a protected file:

# echo "new line of text" | sudo tee -a /path/to/file.txt

Example #7: Restart a Service

You need the sudo command to restart a service on a server. For instance, use the following commands to install and restart Apache on your system:

# sudo apt-get install apache2
# sudo systemctl restart apache2

install apache 2

restart apache 2

Example #8: Install a Package on a System

You need the sudo privileges to install a package on Debian-based Linux distributions. Here’s the syntax of this command: # sudo apt-get install packagename

Example #9: Edit a System Configuration File

All system configuration files on a Linux system are protected by default. You need sudo privileges to access and edit these files. For instance, the following command uses the nano editor with sudo permissions to edit the hosts files (that contains the IP mapping information):

# sudo nano /etc/hosts

Example #10: View Protected Log Files

You need sudo privileges to view log files on your Linux system. For instance, the following command outputs the contents of the syslog file in the terminal:

# sudo cat /var/log/syslog

sudo cat syslog

Example #11: Add a New User Account

Use the following command to create a new user account:

# sudo adduser newusername

Example #12: Change File Owners

Use the sudo command to change the ownership of a file:

# sudo chown username:groupname filename

Example #13: Change Hostname

Change the system’s hostname with the following command:

# sudo hostnamectl set-hostname newhostname

Example #14: List Disk Usage

Use the following syntax to check disk usage by directories:

# sudo du -sh /var/*

Example #15: Kill a Process

You can easily kill a process with the sudo privileges. Note that you need to know the process ID for this command:

# sudo kill -9 PID

Conclusion

Mastering sudo is a crucial skill in efficient Linux system management. Whether you’re administering a personal laptop or managing servers(like those provided by RedSwitches Bare Metal Hosting), understanding sudo elevates your control and security in the Linux environment.

If you’re looking for a robust server for your Linux projects, RedSwitches offers the best dedicated servers pricing and delivers instant dedicated servers, usually on the same day the order gets approved. Whether you need a dedicated server, a traffic-friendly 10Gbps dedicated server, or a powerful bare metal server, we are your trusted hosting partner.

FAQ

Q. What is the purpose of the sudo command in Linux?

The sudo command in Linux allows a permitted user to execute a command as the superuser or another user, as specified by the security policy.

Q. How do I use the sudo command in Linux?

To use the sudo command in Linux, you simply type “sudo” followed by the command you want to execute with elevated privileges.

Q. What is the difference between su and sudo su?

The su command allows you to switch to another user, while sudo su allows you to switch to the superuser account with the sudo command.

Q. How can I set a password timeout for the sudo command?

You can set a password timeout for the sudo command by editing the sudoers file using the visudo command and configuring the default timestamp_timeout option.

Q. Can I run a command in the background with sudo?

Yes, you can run a command in the background with sudo by adding an ampersand (&) at the end of the command.

Q. What is the purpose of the visudo command?

The visudo command is used to edit the sudoers file safely. The utility locks the sudoers file and provides warnings about syntax errors before saving any changes.

Q. How can I allow a regular user to run commands as a super user?

You can allow a regular user to run commands as a superuser by adding the user to the sudo group in the sudoers file.

Q. What are the important considerations when using the sudo command?

When using the Linux sudo command, it’s important to understand that with great power comes great responsibility, and you should be mindful of the commands you execute with elevated privileges.

Q. What should the system administrator do if he forgets the root password?

If you forget the root password, you can use the sudo command with a user with sudo access to perform administrative tasks without needing the root password.

Q. How can I learn how to use the sudo command with elevated privileges?

To learn how to use the sudo command with elevated privileges, you can use the following resources and practice executing commands as a sudo user on different distributions of Linux.

Try this guide with our instant dedicated server for as low as 40 Euros