Kiến Thức Linux

How to Use the Linux sudo Command

sudo Command in Linux with Examples

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.

Option Description
-h Displays help information and exits.
-V Displays version information and exits.
-v Updates the user’s timestamp without running a command.
-k Invalidates the user’s timestamp, forcing the user to re-enter their password the next time sudo is used.
-K Removes the user’s timestamp entirely, similar to -k.
-b Runs the given command in the background.
-n Non-interactive mode; if a password is required, sudo shows an error.
-H Sets the HOME environment variable to the target user’s home directory.
-i Simulates an initial login session, running the shell as a login shell.
-e Edits files safely with elevated privileges.
-s Starts a shell with root privileges.
-u Runs the command as a specified user.
-g Runs the command as a specified group.
-l Lists the user’s allowed and forbidden commands.
-A Uses an alternate method for password authentication.
-E Preserves 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:

Variable Description
EDITOR Sets 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.
HOME Set to the target user’s home directory when using the -s or -H options with sudo.
PATH Set to a secure and predefined value if the secure_path option is enabled in the sudoers configuration file.
SHELL Determines which shell to run when using the -s option with the sudo command.
SUDO_PROMPT Used as the default password prompt.
SUDO_COMMAND Records the command being executed.
SUDO_USER Tracks the original user who initiated the sudo command.
SUDO_UID Provides the user ID.
SUDO_GID Provides the group ID of the user, useful for maintaining correct group permissions and auditing.
SUDO_PS1 Customizes the shell prompt when running a command with sudo.
USER Defines the target user for the sudo command, ensuring commands are executed with the appropriate user context.
VISUAL Ensures 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.

Đăng ký liền tay Nhận Ngay Bài Mới

Subscribe ngay

Cám ơn bạn đã đăng ký !

Lỗi đăng ký !

Add Comment

Click here to post a comment

Đăng ký liền tay
Nhận Ngay Bài Mới

Subscribe ngay

Cám ơn bạn đã đăng ký !

Lỗi đăng ký !