How to Use the Linux sudo Command

June 6, 2024

Introduction

sudo (SuperUser DO) command lets you access restricted files and operations. By default, Linux restricts access to certain system parts to prevent sensitive files from being compromised.

The sudo command temporarily elevates privileges, allowing users to complete sensitive tasks without logging in as the root user.

In this tutorial, learn how to use the sudo command in Linux with examples.

sudo Command in Linux with Examples

Prerequisites

  • A system running Linux (this tutorial uses Ubuntu 22.04).
  • Access to the terminal.
  • A user account with sudo.

sudo Command Syntax

The sudo command syntax is simple:

sudo [command]

When you run the sudo command, a timestamp is recorded in the system logs. This allows users to run commands with elevated privileges for a short time (15 minutes by default). If someone without sudo privileges attempts to use the sudo command, it is logged as a security event.

Note: There are several ways to create a sudo user. Check out how to create a sudo user on Ubuntu, Debian, or Centos.

sudo Options

Command options enhance the functionality and security of sudo in various situations. The following table presents options commonly used with sudo.

OptionDescription
-hDisplays help information and exits.
-VDisplays version information and exits.
-vUpdates the user's timestamp without running a command.
-kInvalidates the user's timestamp, forcing the user to re-enter their password the next time sudo is used.
-KRemoves the user's timestamp entirely, similar to -k.
-bRuns the given command in the background.
-nNon-interactive mode; if a password is required, sudo shows an error.
-HSets the HOME environment variable to the target user's home directory.
-iSimulates an initial login session, running the shell as a login shell.
-eEdits files safely with elevated privileges.
-sStarts a shell with root privileges.
-uRuns the command as a specified user.
-gRuns the command as a specified group.
-lLists the user's allowed and forbidden commands.
-AUses an alternate method for password authentication.
-EPreserves the user's environment when running a command.
--Indicates the end of sudo options.

Note: Staying logged in as an administrator compromises security. Admins used to run the su (substitute user) command to temporarily switch to an administrator account. However, the su command requires a second user account and password, which isn't always feasible.

Environment Variables Used by sudo

Environment variables in sudo provide control and customization over the sudo command behavior and the environment in which commands run. The following table provides a detailed explanation of each variable:

VariableDescription
EDITORSets the default editor to use with the -e option if VISUAL is not set. Allows you to safely edit files as root without running the editor as root. Copies the file to a temporary location, edits it, and then moves it back with root privileges.
HOMESet to the target user's home directory when using the -s or -H options with sudo.
PATHSet to a secure and predefined value if the secure_path option is enabled in the sudoers configuration file.
SHELLDetermines which shell to run when using the -s option with the sudo command.
SUDO_PROMPTUsed as the default password prompt.
SUDO_COMMANDRecords the command being executed.
SUDO_USERTracks the original user who initiated the sudo command.
SUDO_UIDProvides the user ID.
SUDO_GIDProvides the group ID of the user, useful for maintaining correct group permissions and auditing.
SUDO_PS1Customizes the shell prompt when running a command with sudo.
USERDefines the target user for the sudo command, ensuring commands are executed with the appropriate user context.
VISUALEnsures the preferred text editor is used when editing files.

Examples of sudo in Linux

sudo was developed as a way to grant a user administrative rights temporarily. To make it work, use sudo before a restricted command. The following text provides practical sudo usage examples.

Basic sudo Usage

The basic sudo function is to run commands restricted from regular users. To check what a restricted command looks like with and without sudo, take the following steps:

1. Open a terminal window and run the following command:

apt update

An error message appears. You do not have the necessary permissions to run the command.

apt update terminal output

2. Try the same command with sudo:

sudo apt update

3. Type your password when prompted. The system executes the command and updates the repositories.

sudo apt update terminal output

Run Command as a Different User

sudo also allows you to run a command as another user:

1. Verify your username with the whoami command:

whoami
whoami terminal output

The system displays your username.

2. Run the following command:

sudo -u [different_username] whoami

For example, we use user1:

sudo -u user1 whoami
sudo -u user1 whoami terminal output

Switch to Root User

The command sudo bash is used to start a BASH shell with root privileges.

sudo bash
sudo bash terminal output

The prompt changes to indicate the shell is now running as the root user.

Execute Previous Commands with sudo

The Linux command line keeps a record of previously executed commands. Access these records by pressing the up arrow. To repeat the last command with elevated privileges, use:

sudo !!
sudo !! terminal output

This also works with earlier commands. Specify the historical number as follows:

sudo !16
sudo !16 terminal output

This example repeats the 16th entry in history with the sudo command.

To learn about how to efficiently use the history command, check out our article on sudo history command with examples.

Run Multiple Commands in One Line

String multiple commands together, separated by a semicolon. For example, run ls, whoami, and hostname:

sudo ls; whoami; hostname
sudo ls; whoami; hostname terminal output

Add a String of Text to an Existing File

Use sudo to add a text string to an existing file without opening it for editing. This method is often employed for tasks such as adding repository URLs to sources list files in Linux. Use the following syntax with echo, sudo, and tee command:

echo 'string-of-text' | sudo tee -a [path_to_file]

For example:

echo "deb http://nginx.org/packages/debian $(lsb_release -cs) nginx" | sudo tee /etc/apt/sources.list.d/nginx.list
terminal output for the echo command

The command adds the Nginx software repositories to your system.

Conclusion

This article explained the sudo command and how to use it. Refer to the examples to learn how to use the command efficiently.

Next, learn the difference between the sudo and su command.

Was this article helpful?
YesNo
Sara Zivanov
Sara Zivanov is a technical writer at phoenixNAP who is passionate about making high-tech concepts accessible to everyone. Her experience as a content writer and her background in Engineering and Project Management allows her to streamline complex processes and make them user-friendly through her content.
Next you should read
How To Add User to Sudoers & Add User to Sudo Group on CentOS 7
December 5, 2018

This guide will walk you through the steps to create or add a sudo user on CentOS 7. The sudo command...
Read more
How To Add User To Sudoers & Add User To Sudo Group on Ubuntu
April 3, 2024

The sudo command is the preferred means to handle elevated permissions. Standard user accounts are restricted...
Read more
How to Change Sudo or Root Password in Ubuntu
April 16, 2024

Are you looking to change the root password in Ubuntu? Changing passwords is a good practice and should be...
Read more
How to Create a Sudo User on Debian
April 24, 2024

Sudo stands for superuser do. Sudo is a command used in Unix-like systems to allow a regular user to execute...
Read more