sudo, su and root
root is the administrator account: it can change anything, including breaking the system. Normal user pi cannot install software, edit files in /etc or start services. sudo lets pi do those things one command at a time.
sudo: one command as root
sudo apt install apache2
sudo nano /etc/apache2/apache2.conf
sudo systemctl restart apache2
It may ask for your password (pi's). On the lab image it usually does not ask at all.
When do you need sudo?
| Task | sudo? |
|---|---|
Install/remove software (apt) | Yes |
Edit anything in /etc, /var/www/html | Yes (unless you changed the owner) |
| Start/stop/restart services | Yes |
systemctl status | No |
Read and edit files in /home/pi | No |
| Run your Python scripts | No |
pip install inside the venv | No, never |
Do not "just add sudo" to everything. Running Thonny, Python, pip or nano on your own files with sudo creates files owned by root that pi can no longer save or change. That causes "Permission denied" errors later that look unrelated.
su and root shells
| Command | What it does |
|---|---|
sudo -i | A root shell: every command is root until exit. Prompt ends in #. |
su - otheruser | Become another user, with their password |
su - | Become root with root's password. Root has no password on Raspberry Pi OS, so this fails: use sudo -i. |
exit | Back to your own user |
In a root shell, look at the prompt before every command. # means there is no safety net.
sudo and MariaDB
sudo mariadb logs in as MariaDB's root because you are Linux root at that moment (unix_socket). That is why it works when every MariaDB password is forgotten. Details: MariaDB users.
Who am I?
whoami # pi or root
id # user id and all groups
sudo -l # what you may run with sudo
sudo with redirection
This fails even with sudo:
sudo echo "ServerName localhost" >> /etc/apache2/apache2.conf # Permission denied
The >> is done by your shell, as pi, before sudo runs. Use tee instead:
echo "ServerName localhost" | sudo tee -a /etc/apache2/apache2.conf
Fixing files you made with sudo by mistake
ls -l # owner "root" on your own files = this problem
sudo chown -R pi:pi /home/pi # give everything in your home back to pi
Common errors
| Error | Meaning and fix |
|---|---|
Permission denied | You need sudo, or the file belongs to root. ls -l to see the owner. |
E: Could not open lock file ... (13: Permission denied) / Are you root? | apt needs sudo. |
pi is not in the sudoers file | Your user is not allowed to use sudo. Log in as an admin user and run sudo usermod -aG sudo pi. |
sudo: unable to resolve host xyz | The hostname was changed but /etc/hosts was not. Fix the 127.0.1.1 line in /etc/hosts (hostname). |
su: Authentication failure | root has no password. Use sudo -i. |
sudo: command not found (after sudo cd) | cd is not a program. Use sudo -i then cd, or just sudo ls /path. |