Linux · Command Cheat Sheet · System Administration

Linux sudo Cheat Sheet: Commands, Options and sudoers

Use this practical sudo reference to run commands with elevated privileges, switch execution users, manage cached credentials, inspect permissions, handle redirection, and configure sudoers safely on Linux servers.

By Khurram Shahzad · October 19, 2026 · Linux Cheat Sheet

Linux sudo command cheat sheet with terminal examples and security shield
A quick reference to safer privilege escalation with sudo.
Quick guidance: use sudo command for one privileged task, sudo -l to inspect allowed commands, and sudo visudo to safely edit sudoers policy. Avoid granting unrestricted passwordless access unless it is explicitly justified.

What is sudo?

sudo lets an authorized user execute a command as another user, usually root. The sudoers policy determines which commands are permitted and under what conditions. This makes it possible to delegate administrative tasks without sharing the root password.

Commands below are common OpenSSH/Linux administration patterns, but exact options, group names, defaults, and log locations can differ by distribution and sudo version. Check the local manual with man sudo and man sudoers before changing security policy.

1. Basic sudo commands

CommandPurpose
sudo commandRun one command as the default target user, usually root.
sudo -u username commandRun a command as a specified user.
sudo -g groupname commandRun with a specified primary group, if policy permits.
sudo -iStart a root login shell with the target user’s login environment.
sudo -sStart a shell as the target user without requesting a login shell.
sudo -e /etc/hostsEdit a protected file using sudo’s edit mode.
sudo -b commandStart the command in the background.
sudo -- command --helpStop sudo option parsing so subsequent options are passed to the command.
sudo !!In Bash or Zsh, rerun the previous history command with sudo; shell history expansion must be enabled.
Best practice: prefer a single sudo command when possible. An interactive root shell such as sudo -i is powerful and can make accidental system-wide changes easier.

2. Password caching and prompts

Command or settingWhat it does
sudo -vValidate or refresh cached credentials without running another command.
sudo -kInvalidate the current terminal’s cached timestamp; the next privileged command may prompt again.
sudo -KRemove cached credentials for the invoking user.
sudo -n commandDo not prompt; fail if authentication would require an interactive prompt.
sudo -A commandUse the configured askpass helper to obtain a password when supported and configured.
sudo -p "Password for %u: " commandUse a custom password prompt.
Defaults timestamp_timeout=10Example sudoers setting: cache credentials for ten minutes.
Defaults timestamp_timeout=0Require authentication for each command according to policy.

Credential timeout defaults vary. Linuxize reports a 15-minute default for Debian/Ubuntu packages and a five-minute upstream default used by Fedora/RHEL. Verify the actual policy on your system rather than assuming one value applies everywhere.

Check whether cached credentials remain valid without prompting

sudo -n -v

This exits successfully if sudo can validate credentials without prompting; otherwise it returns a nonzero status. In scripts, check the exit code instead of assuming a password prompt will be available.

3. Check your sudo privileges

CommandPurpose
sudo -lList commands the current user may run.
sudo -llDisplay matching privileges in long form.
sudo -l -U usernameInspect another user’s privileges when authorized.
sudo -l /usr/bin/systemctlCheck whether a particular command is permitted; behavior depends on the installed sudo version and policy.
sudo -VDisplay sudo version and configuration information.
id -nGList the current user’s group names.
getent group sudoShow the sudo group entry on distributions that use this group.

Group names differ: Debian and Ubuntu commonly use sudo, while Fedora and RHEL commonly use wheel. Membership is not the whole policy; sudoers rules and included configuration files determine the effective permission set.

4. Environment handling

Command or settingPurpose
sudo -E commandRequest preservation of the caller’s environment, subject to policy.
sudo --preserve-env=http_proxy commandRequest preservation of a named variable, subject to policy.
sudo -H commandRequest setting HOME to the target user’s home directory.
sudo envInspect the environment passed to the command.
Defaults env_resetUse a restricted environment as the basis for privileged commands.
Defaults secure_path="/usr/sbin:/usr/bin:/sbin:/bin"Example PATH policy for privileged commands; use paths appropriate to the system.

Environment preservation is not guaranteed: sudoers policy can reject or filter variables. Avoid preserving untrusted environment variables into privileged commands, particularly variables that influence executable lookup, library loading, or configuration.

5. Redirects, pipes, and multiple commands

The shell processes redirection before launching sudo. As a result, this common example usually fails when the current user cannot write to /root:

sudo echo "test" > /root/file.txt

Use tee to write through a privileged process:

echo "test" | sudo tee /root/file.txt
echo "another line" | sudo tee -a /root/file.txt

Or run a shell that performs the redirection as root:

sudo sh -c 'echo "test" > /root/file.txt'

Only the command immediately launched by sudo runs with elevated privileges. In a pipeline such as sudo cat /etc/shadow | wc -l, cat runs as root while wc runs as the current user.

To run a sequence with shell operators under a privileged shell:

sudo sh -c 'cd /root && ls -l | wc -l'

Quote the command string so the current shell does not process the operators before the privileged shell receives them. Use this pattern cautiously because every command inside the quoted string runs with the shell’s elevated privileges.

6. Edit sudoers safely

Use visudo rather than editing /etc/sudoers directly. It checks the policy syntax before saving, helping prevent a typo from breaking sudo access.

sudo visudo

For maintainability, many distributions support drop-in files under /etc/sudoers.d/. Create them with visudo -f so the file is checked:

sudo visudo -f /etc/sudoers.d/ops-team

Example rule granting a user permission to run one exact command:

opsuser ALL=(root) /usr/bin/mkdir

This is an illustrative policy rule. Verify the actual executable path with command -v mkdir and consider whether arguments must also be restricted. Do not assume that allowing an editor, interpreter, pager, or other powerful executable is a safe narrow permission: many programs can launch child commands or otherwise escape their apparent task.

7. sudoers rule syntax and examples

A common sudoers rule has the general form:

user host=(runas_user:runas_group) tags: commands
Example ruleMeaning / caution
username ALL=(ALL:ALL) ALLBroad administrative access for the named user.
%sudo ALL=(ALL:ALL) ALLCommon Debian/Ubuntu group rule.
%wheel ALL=(ALL) ALLCommon Fedora/RHEL group rule.
username ALL=(ALL) NOPASSWD: ALLUnrestricted commands without a password prompt; high risk and generally unsuitable as a default.
username ALL=(root) /usr/bin/systemctl restart nginxExample command-specific grant; confirm command path and argument matching behavior.
username ALL=(www-data) /usr/bin/phpAllows running a command as a service account, subject to the policy’s command matching.
Defaults timestamp_timeout=15Example timeout setting; check local distribution defaults and policy precedence.
Defaults passwd_tries=3Example limit on password attempts.
Security warning: sudoers wildcards can match more than a single intended argument, and allowing an executable may allow indirect command execution. Use the narrowest practical command, arguments, target user, and scope. Validate every change with visudo and test it in a separate session before closing your administrative session.

8. Logging and auditing

Command or settingPurpose
sudo journalctl _COMM=sudoSearch systemd journal entries associated with sudo on systems that record them there.
sudo journalctl -t sudo -S todaySearch journal entries with the sudo syslog identifier from today.
sudo grep sudo /var/log/auth.logCheck the common authentication log on Debian/Ubuntu systems that use this file.
sudo grep sudo /var/log/secureCheck the common secure log on Fedora/RHEL systems that use this file.
Defaults logfile="/var/log/sudo.log"Example configuration for a dedicated sudo log file.
Defaults log_input, log_outputEnable input/output logging where supported and configured; consider privacy and storage requirements.
sudo sudoreplay -lList recorded sessions when I/O logging is enabled.

Logging behavior depends on the local sudoers policy and system logging configuration. A privileged interactive shell is especially important to account for: ordinary sudo logs may record the shell launch, but not necessarily every command typed inside that shell unless I/O logging or another auditing mechanism is configured.

9. Common sudo troubleshooting

“User is not in the sudoers file”

Check group membership and the configured policy:

id -nG
sudo -l

If you do not have administrative rights, ask an authorized administrator to grant the minimum required access. Adding a user to an administrative group requires an existing root or administrator session.

“Permission denied” when redirecting output

The current shell likely opened the destination before sudo ran. Use sudo tee or a carefully quoted privileged shell, as shown above.

“Command not found” after using sudo

Sudo may use a restricted PATH. Use the verified absolute path of the command and inspect the effective policy. Do not solve this by indiscriminately adding writable directories to the privileged PATH.

sudo asks for a password in a script

For non-interactive scripts, sudo -n command fails instead of waiting for input. Configure a narrowly scoped policy for the required operation rather than granting NOPASSWD: ALL.

Concerned that credentials remain cached

Use sudo -k to invalidate the current terminal’s timestamp, or sudo -K to remove cached credentials for the invoking user. Exact behavior may vary with the sudo version and timestamp configuration.

10. Quick reference: the commands to remember

TaskCommand
Run one command as rootsudo command
Run as another usersudo -u username command
Open a root login shellsudo -i
Inspect privilegessudo -l
Refresh credentialssudo -v
Invalidate current terminal’s cachesudo -k
Run without promptingsudo -n command
Safely edit sudoerssudo visudo
Write a root-owned fileecho "text" | sudo tee /root/file
Check versionsudo --version

Conclusion

sudo is a core Linux administration tool for delegating privileged operations while preserving individual user identities and policy controls. Learn the basic command patterns, understand password caching, inspect effective privileges, and use visudo to edit rules safely.

For production servers, grant only the access needed for each role, avoid unrestricted passwordless rules, protect environment and PATH handling, and confirm local defaults rather than copying policy assumptions between distributions.

Official references and further reading

VMoreCloud takeaway: use sudo to grant controlled administrative access, verify permissions before relying on them, and keep sudoers rules as narrow and auditable as practical.
Khurram Shahzad
Hybrid Cloud & Virtualization Engineer

Hybrid Cloud & Virtualization Engineer specializing in VMware, Azure, AWS, Windows Server, Microsoft 365, Linux, networking, backup & disaster recovery. I share practical guides, technical projects and insights into modern IT infrastructure through VMoreCloud.

Leave a Reply

Your email address will not be published. Required fields are marked *

Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.

Powered By
Best Wordpress Adblock Detecting Plugin | CHP Adblock