CIS120 Linux Fundamentals by Scott Shaper

sudo and su commands

Think of sudo and su like different ways to get special access. sudo is like having a temporary key card for specific tasks, while su is like changing your identity completely. Understanding when to use each command helps you work safely and efficiently.

Note: You do not have sudo access on the Cidermill server. However, it is still important to understand what sudo and su do.

Quick Reference

Command What It Does When to Use
sudo command Run single command as root Quick admin tasks like installing software
su Switch to root user Extended root sessions
su username Switch to another user Working as different user

When to Use Each Command

Basic sudo Usage

Think of sudo like a temporary promotion - it gives you special powers just for the command you're running.

Common Examples

# Install software
sudo apt install package-name

# Edit system configuration
sudo nano /etc/config-file

# Restart a service
sudo systemctl restart service-name

# Check disk space
sudo df -h

# View system logs
sudo journalctl -xe

Understanding su (Switch User)

Think of su like changing your identity completely - it lets you switch to another user account, including the root user. While sudo gives temporary privileges, su actually changes your user context.

su Examples

# Switch to root user
su
# Enter root password

# Switch to specific user
su username
# Enter user's password

# Switch to root with environment
su -

# Switch to user with environment
su - username

# Exit back to your original user
exit

Understanding sudo Options

Option What It Does When to Use
-i Start interactive root shell Multiple admin tasks in sequence
-u username Run as specific user Testing user permissions
-l List allowed commands Checking your sudo privileges
-v Extend sudo timeout Keeping sudo active longer

Option Examples

# Start root shell
sudo -i

# Run command as another user
sudo -u username command

# See what you're allowed to do
sudo -l

# Extend sudo timeout
sudo -v

Tips for Success

Common Mistakes to Avoid

Best Practices

Advanced Techniques

Combining Commands

# Run multiple commands with one sudo
sudo sh -c 'command1 && command2'

# Use sudo in scripts
#!/bin/bash
if [ "$(id -u)" != "0" ]; then
    echo "This script must be run as root" 1>&2
    exit 1
fi

# Run commands as different users
sudo -u user1 command1
sudo -u user2 command2

# Use sudo with pipes
sudo cat /etc/passwd | grep username

Security Considerations

Think of sudo and su like powerful tools - they're useful but need to be handled carefully:

Security Examples

# Check file permissions before editing
ls -l /etc/config-file
sudo nano /etc/config-file

# Use specific commands instead of root shell
sudo apt update
sudo apt upgrade

# Set shorter sudo timeout
sudo visudo
# Add: Defaults timestamp_timeout=5