The Super User — root and sudo
Asha's garden club now runs a small server, and she needs to install a program and edit a file in /etc. Her normal account isn't allowed to do either, and that's deliberate. Linux keeps one all-powerful account, root, and makes you ask on purpose each time you need its power.
The rule
sudo lifts one command; the rest of the line is still you.
root is the administrator account, with user ID 0. It can read, change or delete anything, and the system doesn't ask whether you're sure. Logging in as root for everyday work is risky, so most systems give trusted users sudo instead:
$ sudo apt install tree
[sudo] password for asha:sudoruns one command as root. It asks for your own password, not root's.- Only users listed in the sudo rules can use it, which usually means members of a group such as
sudoorwheel. The rules live in/etc/sudoers, and you edit that file safely withvisudo. - After you type your password,
sudousually doesn't ask again for a few minutes. - Each use can be logged, so there's a record of who did what.
Related commands:
| Command | Does |
|---|---|
sudo command |
run one command as root |
sudo -u ravi command |
run a command as another user |
sudo -i |
open a root shell; exit leaves it |
su - |
switch to root; needs root's password |
sudo !! |
Bash: re-run your last command with sudo |
whoami / id |
show who you are right now |
A # at the end of the prompt usually means you're root, and $ means you're a normal user.
The shortcut
Before running anything with sudo, split the line into parts and ask "who does this part?" sudo only raises the command that comes right after it. Redirects (>, >>) and any command after a pipe are still handled by your own, ordinary shell.
The first attempt
sudo echo "192.168.1.20 garden-server" >> /etc/hostssays "Permission denied".
Two good habits: keep sudo for the single command that needs it rather than staying in a root shell, and read a command carefully before you give it root's power. sudo rm -r has no undo.
Drills
Answer fast — trust the rule.
Whose password does sudo normally ask for?
Why does sudo echo hi > /etc/motd fail with "Permission denied"?
Which is the safe way to edit the sudo rules?
Asha runs apt update, gets "Permission denied", and wants to repeat it with root rights. What's the Bash shortcut?
Remember
- sudo lifts one command; the rest of the line is still you.
- Split the line and ask who does each part. Redirects and piped commands run as you, so use
sudo teeto write protected files. - root has user ID 0, and a
#prompt usually means you're root. Use sudo sparingly and read the command before you run it.
