🎁 New User? Get 20% off your first purchase with code NEWUSER20 Register Now →
Menu

Categories

sudo Command

Beginner User Management man(1)

Execute a command as another user (typically root)

👁 11 views 📅 Updated: Mar 15, 2026
SYNTAX
sudo [OPTION]... COMMAND

What Does sudo Do?

sudo (superuser do) executes a command as another user, typically root. It is the primary mechanism for administrative privilege escalation in Linux, providing fine-grained access control through the /etc/sudoers file.

sudo logs all commands for auditing, requires the user's own password (not root's), and can be configured to allow specific commands for specific users. It is far more secure than logging in as root or using su.

sudo is configured via /etc/sudoers (edited with visudo). Users must be in the sudo group (Debian/Ubuntu) or wheel group (RHEL/CentOS) to use sudo by default.

Options & Flags

OptionDescriptionExample
-u Run as specified user sudo -u www-data php script.php
-i Login shell as root sudo -i
-s Run a shell as root sudo -s
-l List allowed commands sudo -l
-k Invalidate cached credentials sudo -k
-v Extend credential timeout sudo -v
-E Preserve environment variables sudo -E ./script.sh
-n Non-interactive (fail if password needed) sudo -n systemctl status nginx

Practical Examples

#1 Run as root

Runs apt update with root privileges.
$ sudo apt update

#2 Edit protected file

Opens a root-owned file for editing.
$ sudo nano /etc/nginx/nginx.conf

#3 Run as another user

Opens PostgreSQL as the postgres user.
$ sudo -u postgres psql

#4 Root login shell

Opens a full root login shell with root environment.
$ sudo -i

#5 Check permissions

Shows what commands you are allowed to run with sudo.
$ sudo -l
Output: (ALL : ALL) ALL

#6 Run last command as root

Re-runs the previous command with sudo prepended.
$ sudo !!

Tips & Best Practices

Use sudo, not root login: Never log in as root directly. sudo provides auditing, limited scope, and uses your own password. Root login disables all these safeguards.
sudo !! for mistakes: Forgot sudo? Type sudo !! to re-run the last command with root privileges.
Password caching: sudo caches your password for 15 minutes by default. Use sudo -k to clear it immediately.

Frequently Asked Questions

How do I run a command as root?
Prefix it with sudo: sudo command. You will be prompted for your own password (not root password).
How do I become root?
Use sudo -i for a root login shell or sudo -s for a root shell. Exit with exit or Ctrl+D.
How do I add a user to sudoers?
Use: sudo usermod -aG sudo username (Debian/Ubuntu) or sudo usermod -aG wheel username (RHEL/CentOS).

Master Linux with Professional eBooks

Curated IT eBooks covering Linux, DevOps, Cloud, and more

Browse Books →