|

Linux CLI 19 ๐Ÿง su and sudo commands

Two commands for running things as another user โ€” usually as root. They look similar but serve different purposes and have different security models.


Overview

CommandFull NamePurpose
suSubstitute UserSwitch to another user (usually root)
sudoSuperUser DORun a single command with elevated privileges

Key difference:

  • su โ€” needs the target user’s password (e.g., root’s password)
  • sudo โ€” needs your own password (and you must be authorized in sudoers)

The su Command

Switches to another user โ€” usually root.

ls /root
su -
su -l
exit
su -c 'ls /root'
CommandDescription
suSwitch to root (but keeps current environment)
su -Switch to root with a login shell (full environment)
su -lSame as su -
su -l usernameSwitch to a specific user
exitReturn to your original user
su -c 'command'Run one command as root

su vs su - โ€” Why the Dash Matters

Without -With -
Keeps your current environmentLoads target user’s environment
Stays in your current directoryChanges to target user’s home
Uses your PATH, $HOME, etc.Uses target’s PATH, $HOME, etc.

Visual:

su :     Your env โ”€โ”€โ”€โ”€โ†’ Root shell (same env)
su -  :  Login shell โ”€โ”€โ†’ Root shell (root's env)

su -:
  HOME=/root
  PWD=/root
  PATH=/usr/sbin:/usr/bin:/sbin:/bin
  USER=root

su (without -):
  HOME=/home/kronos        โ† still yours!
  PWD=/home/kronos         โ† still yours!
  USER=kronos              โ† env not updated!

Best practice: Use su - โ€” not plain su. It gives you a proper login shell with the correct environment.


Examples

Check what’s in /root:

$ ls /root
ls: cannot open directory '/root': Permission denied

Switch to root:

$ su -
Password: ************
root@olympos:~#
# Prompt changes from $ to #

Run one command as root:

$ su -c 'ls /root'
Password:
# (shows contents of /root)
# Returns to your normal user afterward

Switch to another user:

$ su -l alice
Password:
alice@olympos:~$

Exit back:

root@olympos:~# exit
$

How to Spot You’re Root

PromptUser
$Regular user
#Root
kronos@olympos:~$          โ† regular user
root@olympos:~#            โ† root

The sudo Command

SuperUser DO โ€” run a single command with root privileges.

sudo ls /bin
sudo -l
sudo nano /etc/sudoers
CommandDescription
sudo commandRun command as root
sudo -lList what privileges you have
sudo -iOpen an interactive root shell
sudo -sOpen a root shell (keeps env)
sudo -u user commandRun command as another user
sudo !!Rerun last command with sudo
sudo -kForget cached password

Why sudo Is Preferred

Featuresusudo
Password neededTarget’s (root’s)Your own
Audit trailโŒ Noโœ… Logged
Granular permissionsโŒ All or nothingโœ… Per-command rules
Time-limitedUntil exit5โ€“15 min timeout
Session scopeWhole sessionSingle command
Recommendedโš ๏ธ Legacyโœ… Modern practice

Examples

Run a command as root:

$ sudo ls /bin
[sudo] password for kronos:
# (lists /bin contents)

Check your privileges:

$ sudo -l
User kronos may run the following commands on olympos:
    (ALL : ALL) ALL

Open a root shell:

$ sudo -i
root@olympos:~#
# Same as "su -" but using your own password

Rerun last command with sudo:

$ apt update
Permission denied
$ sudo !!
sudo apt update
# โœ…

Run as another user:

$ sudo -u alice whoami
alice

The sudoers File

Controls who can use sudo and what they can do.

sudo nano /etc/sudoers

โš ๏ธ Always edit with visudo โ€” not a plain editor!

sudo visudo

Why? visudo checks syntax before saving. A broken sudoers file can lock you out of root access entirely.


Template to Add a User

username ALL=(ALL:ALL) ALL
PartMeaning
usernameThe user to authorize
ALLFrom any host
(ALL:ALL)As any user, as any group
ALLRun any command

Example:

kronos ALL=(ALL:ALL) ALL

More Restrictive Examples

Allow only specific commands:

kronos ALL=(ALL) /usr/bin/apt, /usr/bin/systemctl

No password required:

kronos ALL=(ALL) NOPASSWD: ALL

Group-based:

%sudo ALL=(ALL:ALL) ALL
# Any user in the "sudo" group can run everything

Applying Changes

On most modern systems, sudoers changes are immediate. But if you need to reload:

sudo systemctl daemon-reload

For older systems:

sudo visudo -c     # Check syntax
sudo systemctl restart sudo

Complete Example Session

# ============================================
# PART 1: SU COMMAND
# ============================================

# Try to access /root as regular user
$ ls /root
ls: cannot open directory '/root': Permission denied

# Switch to root with su
$ su -
Password: ************
root@olympos:~# ls /root
# (shows contents)

# Exit back to user
root@olympos:~# exit
logout
$

# Switch to root with su -l (same as su -)
$ su -l
Password:
root@olympos:~#

# Execute one command as root
$ su -c 'ls /root'
Password:
# (shows /root contents, then returns)

# Switch to a specific user
$ su -l alice
Password:
alice@olympos:~$

# ============================================
# PART 2: SUDO COMMAND
# ============================================

# Run a command with sudo
$ sudo ls /bin
[sudo] password for kronos:
# (lists /bin)

# Check privileges
$ sudo -l
User kronos may run the following commands on olympos:
    (ALL : ALL) ALL

# Open root shell
$ sudo -i
root@olympos:~#

# Run as another user
$ sudo -u alice whoami
alice

# Rerun last command with sudo
$ apt update
Permission denied
$ sudo !!
sudo apt update
# โœ…

# ============================================
# PART 3: SUDOERS FILE
# ============================================

# Edit safely with visudo
$ sudo visudo

# Add a new user
# At the end of the file:
kronos ALL=(ALL:ALL) ALL

# Save: Ctrl+X, then Y, then Enter

# Apply changes (usually automatic)
$ sudo systemctl daemon-reload

# Verify new user can sudo
$ sudo -l -U alice

# ============================================
# PART 4: PRACTICAL EXAMPLES
# ============================================

# Install software
$ sudo apt install nginx

# Edit a system file
$ sudo nano /etc/hosts

# Restart a service
$ sudo systemctl restart nginx

# View system logs
$ sudo tail -f /var/log/syslog

# Manage users
$ sudo useradd alice
$ sudo passwd alice

# Change file ownership
$ sudo chown root:root /etc/important.conf

# ============================================
# PART 5: SUDO VS SU โ€” WHICH TO USE?
# ============================================

# โœ… PREFER: sudo for single commands
$ sudo apt update

# โš ๏ธ USE SPARINGLY: sudo -i for a root shell
$ sudo -i
# ... work as root ...
# exit

# โŒ AVOID: su - as root (uses root's password)
$ su -
# Only when sudo isn't available

Quick Reference

su Options

OptionDescription
suSwitch to root (keeps env)
su -Switch to root with login shell
su -lSame as su -
su -l userSwitch to specific user
su -c 'cmd'Run one command
exitReturn to previous user

sudo Options

OptionDescription
sudo cmdRun command as root
sudo -lList privileges
sudo -iInteractive root shell
sudo -sRoot shell (keeps env)
sudo -u user cmdRun as another user
sudo -kForget cached password
sudo !!Rerun last with sudo

sudoers Syntax

PartMeaning
usernameUser or %group
ALLAny host
(ALL:ALL)Any user, any group
ALLAny command
NOPASSWD:No password required

Best Practices

โœ… Do This:

# Use sudo for one-off commands
sudo apt update

# Use sudo -i for multiple root commands
sudo -i
# ... do work ...
exit

# Use sudo !! after "permission denied"
apt update
sudo !!

# Edit sudoers with visudo
sudo visudo

# Check your privileges first
sudo -l

# Use specific commands in sudoers (least privilege)
kronos ALL=(ALL) /usr/bin/apt, /usr/bin/systemctl

โŒ Don’t Do This:

# Don't edit sudoers with a regular editor
sudo nano /etc/sudoers      # โš ๏ธ Might break it
sudo visudo                 # โœ… Safe

# Don't give NOPASSWD: ALL without thinking
kronos ALL=(ALL) NOPASSWD: ALL   # โš ๏ธ Security risk

# Don't use "su -" for every task
su -
# Use "sudo" instead โ€” better audit trail

# Don't stay logged in as root forever
sudo -i
# ... hours later ...
# Better: log out when done

# Don't share your sudo password
# Never share passwords or credentials!

# Don't use sudo for everything
sudo ls           # โš ๏ธ Unnecessary
ls                # โœ… Use sudo only when needed

Common Pitfalls

PitfallProblemSolution
Forgot sudo passwordCan’t run admin commandsAsk admin for access
Broken sudoers fileLocked out of sudoBoot recovery mode, fix with pkexec
su - without -Wrong environmentAlways use su -
Not in sudo group“Not in sudoers file”Admin adds you to sudo
Password timeoutPrompts againNormal after 5โ€“15 min
sudo on every commandBad habitOnly elevate when needed

Real-World Examples

1. System Update

$ sudo apt update
$ sudo apt upgrade

2. Edit System Config

$ sudo nano /etc/nginx/nginx.conf
$ sudo systemctl restart nginx

3. Install Software

$ sudo apt install docker.io
$ sudo systemctl enable docker

4. Manage Users

$ sudo useradd -m alice
$ sudo passwd alice
$ sudo usermod -aG sudo alice

5. Add a User to sudo Group

$ sudo usermod -aG sudo alice
# Verify
$ groups alice
alice : alice sudo users

6. Run GUI App as Root

$ sudo -H gparted
# -H sets HOME to /root (safer for GUI apps)

7. Check Who Has sudo Access

$ sudo -l -U alice
User alice may run the following commands:
    (ALL : ALL) ALL

$ getent group sudo
sudo:x:27:kronos,alice,bob

8. Emergency โ€” Fix Broken sudoers

# If you broke sudoers, boot into recovery mode
# Then:
$ mount -o remount,rw /
$ visudo
# Fix the problem, save, reboot

Visual: su vs sudo

SU:
  User โ”€โ”€[su -]โ”€โ”€โ†’ Root shell
         password: root's
         
         โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
         โ”‚  Full root shell          โ”‚
         โ”‚  (until "exit")           โ”‚
         โ”‚  No per-command logging   โ”‚
         โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

SUDO:
  User โ”€โ”€[sudo cmd]โ”€โ”€โ†’ Command runs as root
         password: your own
         
         โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
         โ”‚  Single command as root   โ”‚
         โ”‚  Logged in /var/log/auth  โ”‚
         โ”‚  5-15 min password cache  โ”‚
         โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Summary

CommandPurposePassword
su -Switch to rootRoot’s
su - userSwitch to another userUser’s
su -c 'cmd'Run one command as rootRoot’s
sudo cmdRun one command as rootYour own
sudo -iInteractive root shellYour own
sudo -lList privilegesYour own
sudo visudoEdit sudoers safelyYour own

Key takeaways:

  • su switches user โ€” needs target’s password
  • sudo runs one command as another user โ€” needs your own password
  • su - (with dash) gives a proper login shell
  • sudo is preferred โ€” better audit trail, granular control, time-limited
  • sudoers file controls who can use sudo โ€” always edit with visudo
  • Template for new sudoer: username ALL=(ALL:ALL) ALL
  • Use sudo !! after “permission denied” โ€” instant fix
  • Never use NOPASSWD: ALL without a very good reason
  • sudo doesn’t need root’s password โ€” use it instead of su in modern workflows

Remember: su is the classic Unix way โ€” all-or-nothing, session-wide, requiring the root password. sudo is the modern, safer alternative โ€” per-command, audited, and using your own password. Use sudo for nearly everything, and use sudo -i (not su -) when you truly need a root shell. And when you accidentally forget sudo โ€” just type sudo !! and get on with your day!


Stop using slow, ad-bloated tool sites! ๐Ÿคฎ

๐Ÿ”Ž Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
โœ… Finance (Mortgage, Interest, Inflation)
โœ… Tech (Base64, JSON, Dev Suite, IP)
โœ… Health (BMI, BMR, TDEE)
โœ… Productivity (Timer, Workspace, QR)

โšก๏ธ Fast & Private
๐Ÿ”’ No data leaves your device
๐Ÿ’Ž 100% Free

๐Ÿ”— Use it now: https://tools.kandz.me
๐Ÿ”– Bookmark itโ€”youโ€™ll need it later!