Linux sudo Command: Run Commands with Elevated or Another User's Privileges

sudo is a tool that allows a user permitted by security policies to execute a command with the privileges of another user. If the target user is not specified, it generally runs as root, but actual privileges and authentication methods are determined according to the system's sudo policy.

It is useful for performing tasks that require administrative privileges, such as installing packages or managing services, but if a command is entered incorrectly, it can affect the entire system. Before executing, it is essential to check the target files and options and grant the minimum necessary privileges only for required commands.

What is the sudo command?

sudo allows authorized users to run commands as a superuser or another user. It is not simply a tool to give all users administrative privileges, but a structure that controls by policy who can run which command with what user privileges on which host.

The default policy plugin is sudoers, and it typically uses settings from /etc/sudoers and /etc/sudoers.d/. The system compares the execution request with the policy and, if necessary, authenticates the user before executing only the permitted commands.

You can check the detailed execution method on the official sudo manual page, and the policy syntax on the official sudoers manual page.

Basic Syntax and First Execution

The general syntax is as follows.

sudo [options] command [arguments...]

An example of updating the package list on Debian or Ubuntu systems is as follows.

sudo apt update

If authentication is required, it usually asks for the password of the currently logged-in user. It is normal that no characters, including asterisks, are displayed on the screen while typing. Depending on the system policy, it may require the target user's password or another authentication method.

If permission is granted and authentication is successful, only the apt update process runs with the target permission. The entire current shell does not automatically change to an administrator shell.

Frequently Used sudo Options

Option Function Examples of usage and precautions
-u user Execute command as the specified user sudo -u postgres psql
-g group Execute command as the specified group Only groups allowed by policy can be used
-l Check the allowed commands of the current user Useful for checking permissions before execution
-v Check or renew authentication information Update timestamp without executing the command
-k Invalidate the current authentication timestamp Require re-authentication on the next sudo execution
-K Completely remove the user's authentication timestamp Stronger initialization than -k
-i Execute the target user's login shell Used for various administrative tasks but with a broader scope
-s Run shell Check the purpose as it may be affected by the calling environment
-n Non-interactive execution Fail without asking if a password is required
-H Request to set HOME to the target user's home Operates according to policy and is not always necessary
-E Request to preserve user environment variables Must be allowed by policy and use cautiously for security
-e, sudoedit Modify files that require permissions through a safe editing flow sudoedit /etc/example.conf

Running as a different user

Specify the target user with -u

If the target user is omitted, root is usually used. By specifying -u, you can run as another user allowed by the policy.

sudo -u postgres psql

This is useful when you need to execute commands in the context of a service account's file permissions or environment. However, some service accounts have restricted login shells, so first check the purpose and policy of the account.

Checking the execution user

To quickly check which user permissions the current policy actually grants, you can use id.

sudo id
sudo -u postgres id

The actual output depends on the system's user and group configuration. For simple verification, inspecting individual commands is more focused than opening an administrator shell.

Checking allowed permissions and authentication cache

Check commands that can be run with sudo -l

sudo -l shows the default settings and the commands that can be executed for the current user. You can check first before randomly changing settings when you encounter a permission error.

sudo -l

Administrators can check the policies of other users with -U if they have privileges, but regular users usually only check their own permissions.

Renew authentication with sudo -v

sudo -v checks or renews stored authentication information without executing a command. It can be used to prepare authentication status before starting multiple administrative commands.

sudo -v

The default time and scope of the authentication cache depend on the sudoers policy. Not being asked for a password for a certain period does not permit all commands, and each command continues to undergo policy checks.

Clear authentication status with sudo -k

Use sudo -k when you want to require re-authentication at the next execution after using a public terminal or finishing administrative tasks.

sudo -k

-K completely removes the user's authentication timestamp. Check your installed sudo version and policy for detailed differences.

Points to be careful about with command chaining and pipes

sudo only applies to the immediately following command

Only the first apt update in the following command is executed with sudo. The subsequent apt upgrade runs with the current user's permissions.

sudo apt update && apt upgrade

If both commands require administrator privileges, the clearest method is to prepend sudo to each command.

sudo apt update && sudo apt upgrade

To accurately understand the execution conditions of connection operators, you can also refer to How to Use Bash Command Connection Operators.

Both sides of a pipe are separate processes

Each command connected by a pipe is executed separately. In the example below, only the first command runs with target privileges, and grep runs as the current user.

sudo some-command | grep 'pattern'

The read-only filter command often requires only normal user permissions. Instead of giving high permissions to the entire pipeline, narrow it down to only the steps that actually need elevated permissions.

Running an entire shell has a wide scope

You can run multiple commands in a shell with target permissions like sudo sh -c 'command1 && command2', but the quoting rules become complex and the permission scope is broad. For simple tasks, it is preferable to specify sudo for each command as it benefits review and logging.

Why Permission denied occurs in redirection

Output redirection is handled by the current shell

The following command runs only echo with administrative privileges. The > redirection is processed by the current shell before sudo runs, so it may not be able to open protected files.

sudo echo 'value' > /etc/example.conf

Only elevate permissions for necessary writes using tee

When you need to add a short line or overwrite, you can pass standard input to sudo tee.

printf '%s\n' 'value' | sudo tee /etc/example.conf > /dev/null

To append to an existing file, use tee -a. Be sure to check the target path and whether it will overwrite before running.

printf '%s\n' 'value' | sudo tee -a /etc/example.conf > /dev/null

Edit configuration files with sudoedit

If you need to modify multiple lines of settings, sudoedit is more appropriate. It allows you to edit a temporary copy as the current user according to policy, then reflects the changes to the original file.

sudoedit /etc/example.conf

This reduces the scope of privileges compared to running the entire editor with administrative privileges, but actual restrictions on symbolic links and writable directories depend on the sudo version and policy.

Administrative shell: sudo -i and sudo -s

Method Typical behavior Suitable situations
sudo command Execute a single command with the target user's privileges Recommended for most one-time administrative tasks
sudo -i Run a shell that simulates the target user's login environment Necessary when consecutive administrative tasks are required
sudo -s Run the shell specified by the invoking user's shell or environment Understand environmental differences and use a shell if needed

In the administrator shell, sudo is not displayed for each subsequent command, making it difficult to gauge the impact of mistakes. For one or two tasks, use the sudo command format rather than the administrator shell, and if you open a shell, continuously check the prompt and the current user and working directory.

Modify sudoers with visudo

Why shouldn't you edit it directly?

If there is a syntax error in /etc/sudoers, sudo itself may not work. visudo locks the file to prevent simultaneous editing and checks basic validity and syntax before saving.

sudo visudo

You can check the safe editing procedure on the official visudo manual page.

Using separate sudoers.d files

To separate rules by role, you can create separate files under /etc/sudoers.d/. First, confirm that the default sudoers on your system includes this directory, and also check the file naming rules.

sudo visudo -f /etc/sudoers.d/service-maintenance

Some sudoers configurations may ignore items with dots in the filename or ending with a tilde, so it is safer to use simple names with letters, numbers, and hyphens.

Check the entire syntax after modification

To check the syntax of the existing sudoers and included files, use the following command.

sudo visudo -c

A successful check does not mean that the permission design is safe. It is recommended to maintain a separate administrator session, use sudo -l as the target user, test allowed/denied actions, and then end the session.

Basic structure of sudoers rules

Sudoers rules conceptually combine the following items.

user host=(runuser:rungroup) tag: command
Item Meaning Points to check during design
User or group Subjects to which the rule applies Groups are generally represented as %groupname
Host System where the rules are valid Do not excessively broaden the host scope in the central policy
Executing user/group Accounts on which the command will be executed Specify only the necessary accounts rather than ALL
Tag Adjust authentication, execution, and logging behavior Use NOPASSWD and similar features restrictively after assessing the risks
Commands and arguments Executables and optional arguments that are allowed Narrow the scope with absolute paths and fixed arguments

The following is an example that restricts the deploy user to performing only restart and status checks of specified services as root. Before actual application, you should review whether the command indirectly allows execution of other commands or modification of files.

deploy ALL=(root) /usr/bin/systemctl restart webapp.service, /usr/bin/systemctl is-active webapp.service

Since the actual path of executables may vary by system, check with commands like command -v systemctl. If executables in scripts that the user can modify or in directories writable by the user are allowed in sudoers, the user can change their content to execute arbitrary commands with elevated privileges.

Design sudoers with the principle of least privilege

Avoid habitually using ALL and NOPASSWD

Rules like ALL=(ALL) NOPASSWD: ALL effectively grant broad unattended administrative privileges. Even if automation is necessary, you should design it with dedicated accounts, fixed executable files and arguments, logs, secrets protection, and invocation paths.

Be cautious with programs that can escape to a shell

Programs that can call editors, pagers, shells, write arbitrary files, or load plugins may seem like restricted commands but can lead to an administrative shell. Do not judge safety based only on the command name; review the program’s full functionality, environment variables, and configuration files.

Specifically restrict command paths and arguments

Specify commands with absolute paths and, if possible, fix the allowed arguments. Wildcards and negation rules can match unexpected paths or be bypassed, so you must fully understand sudoers’ command matching rules before use.

Record permission changes and review them regularly

For sudo policy changes, it is recommended to record the requester, reviewer, purpose, and expiration conditions. Remove unused accounts and rules, and regularly check for excessive privileges based on actual logs and the results of sudo -l.

Reasons why environment variables and paths change

sudo may not copy the environment as is

The default settings of sudoers can remove dangerous environment variables or set up a restricted environment. PATH, HOME, proxy variables, or language settings may differ from your usual shell, which can change the behavior of commands.

sudo env

To troubleshoot, you can compare it with the env output of a regular user, but review the content before sharing as it may contain tokens or sensitive information.

Use sudo -E cautiously

-E requests the preservation of the calling user's environment by policy. The policy may deny it, and environment values such as library paths, proxies, and execution paths can change the behavior of programs running with elevated privileges. It is generally safer to explicitly allow only the necessary variables in sudoers.

Using sudo in automation

Use -n to prevent waiting for a password

In automated tasks, waiting for interactive password input may cause the task to stop. -n causes it to fail immediately when authentication input is required.

sudo -n /usr/bin/systemctl restart webapp.service

Whether it succeeds or fails should be checked by the exit status and logs. Do not put passwords in scripts or on the command line, as they may be exposed in process lists, shell history, or logs.

Allow only the necessary commands to be non-interactive

If unattended execution is necessary, only allow the designated commands and arguments on a dedicated service account, and ensure the account cannot modify the executable and related settings. Instead of broad NOPASSWD privileges, you can also consider task-specific APIs, systemd services, or helper programs with restricted permissions.

Common errors and solutions

Messages or symptoms Possible cause How to check
user is not in the sudoers file No rules allowed for the user Communicate the necessary commands and purposes to the administrator
not allowed to execute The command/argument combination conflicts with the policy Check the allowed range with sudo -l
command not found The PATH for sudo is different from the user's shell Check absolute path and secure_path
Password requested again Authentication cache expired or terminal/policy differences Check policy and timestamp settings
Permission denied in redirection Current shell tries to open a protected file first Use sudoedit or restricted tee
sudoers syntax error Direct editing or incorrect rules Check with visudo -c in recovery session

Security principles when using sudo

  • Before executing commands copied from the internet or documents, directly check the options and target paths.
  • For commands like sudo rm or those related to disks, partitions, firewalls, and accounts, first verify recovery methods and potential impacts.
  • Do not keep an administrator shell open for a long time for a one-time command.
  • Do not recklessly put passwords, tokens, or private keys in the command line, scripts, or environment variables.
  • Do not grant high privileges to scripts or executables that users can modify.
  • Check the location of sudo logs and retention policies, and in critical environments, review central logging and input/output auditing.

Even if sudo records commands, it does not mean that every individual command executed after sudo sh or shell escape is retained in the traditional command log. Confirm if input/output logging is set up separately.

Frequently Asked Questions

Does sudo always run with root privileges?

If you omit the target user, the default is generally root, but you can specify another user with -u, and whether it is actually allowed is determined by the policy. The key point of sudo is not executing as root only, but running commands with the permissions of another allowed user.

Why doesn't sudo ask for a password?

Recent authentication information may still be valid for the time set by the policy, or the NOPASSWD rule may apply to the command. You can check the policy with sudo -l, and use sudo -k to force it to re-authenticate for the next execution.

Why doesn’t sudo cd change the current directory?

cd is a shell built-in command that changes the working directory of the current shell. Changing the directory in a separate process does not affect the parent shell. To run a command in a specific directory, check if that command supports a working directory option or whether sudo supports -D.

Can the sudoers file be edited with a regular editor?

It is not recommended. You must use visudo because a syntax error could make sudo unusable. You can also edit separate files with sudo visudo -f /etc/sudoers.d/filename and check the entire configuration with sudo visudo -c.

Summary

For a command that requires administrator privileges, use sudo command. To run as a different user, use sudo -u user command. You can check the allowed scope with sudo -l. The authentication status can be updated with -v and invalidated after work with -k.

Use visudo and sudoedit for configuration files, and design sudoers rules based on absolute paths, fixed arguments, and minimum privileges. For other commonly used administrative commands, you can refer to List of Frequently Used Commands in Linux.

More in This Category
Linux tree Command: Display a Directory Tree

Linux tree Command: Display a Directory Tree

Learn how to use the Linux tree command to display directory contents as a readable hierarchy and control depth and filtering, with essential options, practical examples, output interpretation, and common troubleshooting tips.

Linux truncate Command: Shrink or Extend File Size

Linux truncate Command: Shrink or Extend File Size

Learn how to shrink or extend files with Linux truncate, adjust sizes relatively, match a reference file, and distinguish sparse logical size from disk usage.

Linux Tutorial / Hard Links vs. Symbolic Links in Linux: Differences and Examples

Linux Tutorial / Hard Links vs. Symbolic Links in Linux: Differences and Examples

Compare hard and symbolic links through inode and path behavior, then create both kinds of link and observe what happens when the original name changes.

Linux Tutorial / File System Basics: Paths and Key Directories

Linux Tutorial / File System Basics: Paths and Key Directories

Understand the Linux directory tree, read absolute and relative paths, and learn what common directories such as /home, /etc, and /var are used for.

Linux ssh-keygen Command: Generate SSH Keys and Inspect Fingerprints

Linux ssh-keygen Command: Generate SSH Keys and Inspect Fingerprints

Learn how to generate SSH Keys and Inspect Fingerprints with the Linux ssh-keygen command, including practical examples, key options, and important precautions.

Linux dig Command: Query DNS Records in Detail

Linux dig Command: Query DNS Records in Detail

Learn how to query DNS Records in Detail with the Linux dig command, including practical examples, key options, and important precautions.

Linux Tutorial / File Permissions and Safe sudo Use

Linux Tutorial / File Permissions and Safe sudo Use

Learn to read file and directory permissions, practice chmod safely, and understand when to use sudo and how to diagnose access errors.

Linux printf Command: Print Values with a Defined Format

Linux printf Command: Print Values with a Defined Format

Learn how to print Values with a Defined Format with the Linux printf command, including practical examples, key options, and important precautions.

Linux sudo Command: Run Commands with Elevated or Another User's Privileges

Linux sudo Command: Run Commands with Elevated or Another User's Privileges

Learn how to use the Linux sudo command to run approved commands with elevated privileges or as another user, with essential options, practical examples, output interpretation, and common troubleshooting tips.

Linux lsmod Command: List Loaded Kernel Modules

Linux lsmod Command: List Loaded Kernel Modules

Learn how to list Loaded Kernel Modules with the Linux lsmod command, including practical examples, key options, and important precautions.