sudo: become root for one command

Updated November 1, 2026

sudo runs one command as root and then returns you to your normal user. So you need not sit as root all the time.

sudo useradd -m alice     # one command as root
sudo -l                   # what am I allowed
sudo -u alice whoami      # run as alice

Sample output

$ whoami
student
$ sudo whoami
root
$ sudo -l
Matching Defaults entries for student on sandbox:
...
User student may run the following commands on sandbox:
    (ALL) NOPASSWD: ALL

How it works: why not be root all the time

As root one typo is fatal and there is no record of who did what. sudo raises privileges for a single command, logs it, and drops back at once. In the sandbox sudo needs no password, and root is capped anyway: some kernel operations are off, so mistakes are safe.

Common mistakes

The redirection is done by your shell, not by sudo. sudo echo test > /etc/probe.txt fails with bash: /etc/probe.txt: Permission denied: bash opens the file while still running as you, and sudo never gets a turn. The privileges are needed by whatever writes. Two ways around it: sudo sh -c 'echo test > /etc/probe.txt' or echo test | sudo tee /etc/probe.txt.

sudo swaps your PATH for its own. The sudo -l output carries a secure_path line, a list of system directories that the command gets instead of your PATH, and ~/bin is not in it. So mytool runs and sudo mytool answers sudo: mytool: command not found. Give the full path: sudo /home/student/bin/mytool.

On a real server a fresh account is not in sudo. sudo id from such a user asks for a password, accepts it, and answers carol is not in the sudoers file. - the password was right, the rights are missing. The fix is not hand-editing /etc/sudoers but adding the user to a group: usermod -aG sudo carol as root (on RHEL and Fedora the group is wheel). If you do edit the file, use visudo: it checks the syntax and stops you from locking yourself out.

Used in

You need this in the lesson Users and permissions.