Linux System Management

Day-to-day commands and practices for managing a Linux system.

Package Management

Debian/Ubuntu (apt)

# Update package lists
sudo apt update

# Upgrade all packages
sudo apt upgrade

# Full upgrade (handles dependencies better)
sudo apt full-upgrade

# Install a package
sudo apt install package-name

# Remove a package
sudo apt remove package-name

# Remove package and config files
sudo apt purge package-name

# Remove unused dependencies
sudo apt autoremove

# Search for packages
apt search keyword

# Show package info
apt show package-name

# List installed packages
apt list --installed

# Clean package cache
sudo apt clean
sudo apt autoclean

Arch Linux (pacman)

# Sync and upgrade
sudo pacman -Syu

# Install package
sudo pacman -S package-name

# Remove package
sudo pacman -R package-name

# Remove package with dependencies
sudo pacman -Rs package-name

# Search packages
pacman -Ss keyword

# List installed packages
pacman -Q

# Clean cache
sudo pacman -Sc

Fedora/RHEL (dnf)

# Update all packages
sudo dnf upgrade

# Install package
sudo dnf install package-name

# Remove package
sudo dnf remove package-name

# Search packages
dnf search keyword

# Clean cache
sudo dnf clean all

System Information

# System overview
uname -a                    # Kernel info
hostnamectl                 # Hostname and OS info
lsb_release -a              # Distribution info
cat /etc/os-release         # OS details

# Hardware info
lscpu                       # CPU info
free -h                     # Memory usage
df -h                       # Disk usage
lsblk                       # Block devices
lspci                       # PCI devices
lsusb                       # USB devices
sudo lshw -short            # Full hardware summary

# System uptime and load
uptime
w                           # Who's logged in + uptime

Process Management

# List processes
ps aux                      # All processes
ps aux | grep process-name  # Filter by name
pgrep process-name          # Get PID by name

# Interactive process viewer
top
htop                        # Better alternative (install separately)

# Kill processes
kill PID                    # Graceful terminate
kill -9 PID                 # Force kill
killall process-name        # Kill by name
pkill process-name          # Kill by pattern

# Background/foreground
command &                   # Run in background
jobs                        # List background jobs
fg %1                       # Bring job 1 to foreground
bg %1                       # Resume job 1 in background
Ctrl+Z                      # Suspend current process
nohup command &             # Run immune to hangups

Service Management (systemd)

# Service control
sudo systemctl start service-name
sudo systemctl stop service-name
sudo systemctl restart service-name
sudo systemctl reload service-name
sudo systemctl status service-name

# Enable/disable on boot
sudo systemctl enable service-name
sudo systemctl disable service-name

# List services
systemctl list-units --type=service
systemctl list-units --type=service --state=running

# View logs
journalctl -u service-name              # Service logs
journalctl -u service-name -f           # Follow logs
journalctl -u service-name --since today
journalctl -xe                          # Recent errors

# System state
sudo systemctl reboot
sudo systemctl poweroff
sudo systemctl suspend

User Management

# Current user
whoami
id                          # User and group IDs
groups                      # Group memberships

# User management
sudo useradd username
sudo useradd -m username    # Create home directory
sudo userdel username
sudo userdel -r username    # Remove with home directory
sudo passwd username        # Set password
sudo usermod -aG group user # Add user to group

# Switch users
su - username               # Switch user (with environment)
sudo -i                     # Root shell
sudo -u username command    # Run as another user

# List users
cat /etc/passwd
getent passwd

File Permissions

# View permissions
ls -la

# Permission format: rwxrwxrwx (owner/group/others)
# r=read(4), w=write(2), x=execute(1)

# Change permissions
chmod 755 file              # rwxr-xr-x
chmod 644 file              # rw-r--r--
chmod u+x file              # Add execute for owner
chmod go-w file             # Remove write for group/others
chmod -R 755 directory      # Recursive

# Change ownership
chown user file
chown user:group file
chown -R user:group directory

# Special permissions
chmod u+s file              # SUID - run as owner
chmod g+s directory         # SGID - inherit group
chmod +t directory          # Sticky bit - only owner can delete

Disk Management

# Disk usage
df -h                       # Filesystem usage
du -sh directory            # Directory size
du -sh * | sort -h          # Size of items, sorted
ncdu /path                  # Interactive disk usage (install separately)

# Disk partitions
lsblk                       # List block devices
sudo fdisk -l               # Detailed partition info
sudo parted -l              # Partition info

# Mount/unmount
sudo mount /dev/sdb1 /mnt
sudo umount /mnt
mount                       # Show all mounts

# Permanent mounts (edit /etc/fstab)
# UUID=xxx  /mount/point  ext4  defaults  0  2

# Find UUID
sudo blkid

Network Management

# Network info
ip addr                     # IP addresses
ip link                     # Network interfaces
ip route                    # Routing table
hostname -I                 # Quick IP lookup

# Connectivity
ping host
traceroute host
mtr host                    # Better traceroute

# DNS
nslookup domain.com
dig domain.com
host domain.com
cat /etc/resolv.conf        # DNS servers

# Ports and connections
ss -tuln                    # Listening ports
ss -tupn                    # All connections with PIDs
sudo netstat -tuln          # Alternative
sudo lsof -i :port          # What's using a port

# Firewall (ufw - Ubuntu)
sudo ufw status
sudo ufw enable
sudo ufw allow 22           # Allow SSH
sudo ufw allow 80/tcp       # Allow HTTP
sudo ufw deny 23            # Deny telnet

# Firewall (firewalld - Fedora/RHEL)
sudo firewall-cmd --list-all
sudo firewall-cmd --add-service=http --permanent
sudo firewall-cmd --reload

SSH

# Connect
ssh user@host
ssh -p 2222 user@host       # Different port
ssh -i ~/.ssh/key user@host # Specific key

# Generate keys
ssh-keygen -t ed25519 -C "comment"
ssh-keygen -t rsa -b 4096   # RSA alternative

# Copy public key to server
ssh-copy-id user@host

# SSH config (~/.ssh/config)
# Host myserver
#     HostName 192.168.1.100
#     User admin
#     Port 22
#     IdentityFile ~/.ssh/mykey

# Then just: ssh myserver

# SCP - copy files
scp file user@host:/path
scp user@host:/path/file ./
scp -r directory user@host:/path  # Recursive

# SSH tunneling
ssh -L 8080:localhost:80 user@host  # Local forward
ssh -D 1080 user@host               # SOCKS proxy

File Operations

# Navigation
cd /path
cd ~                        # Home directory
cd -                        # Previous directory
pwd                         # Current directory

# Listing
ls -la                      # Long format, all files
ls -lh                      # Human-readable sizes
ls -lt                      # Sort by time
tree                        # Directory tree

# Copy/move/delete
cp source dest
cp -r source dest           # Recursive
mv source dest
rm file
rm -r directory             # Recursive
rm -rf directory            # Force recursive (dangerous!)

# Create
touch file                  # Create empty file
mkdir directory
mkdir -p path/to/directory  # Create parents

# Find files
find /path -name "*.txt"
find /path -type f -mtime -7    # Modified in last 7 days
find /path -size +100M          # Larger than 100MB
locate filename                  # Fast search (needs updatedb)

# Search file contents
grep "pattern" file
grep -r "pattern" directory     # Recursive
grep -i "pattern" file          # Case insensitive
grep -n "pattern" file          # Line numbers

Text Processing

# View files
cat file
less file                   # Pager (q to quit)
head -n 20 file             # First 20 lines
tail -n 20 file             # Last 20 lines
tail -f file                # Follow file updates

# Text manipulation
sort file
sort -n file                # Numeric sort
uniq                        # Remove duplicates (needs sorted input)
wc -l file                  # Line count
cut -d',' -f1 file          # Extract first field
awk '{print $1}' file       # Print first column
sed 's/old/new/g' file      # Replace text

# Comparison
diff file1 file2
diff -u file1 file2         # Unified format

Compression

# tar (archive)
tar -cvf archive.tar files      # Create
tar -xvf archive.tar            # Extract
tar -tvf archive.tar            # List contents

# tar.gz
tar -czvf archive.tar.gz files  # Create compressed
tar -xzvf archive.tar.gz        # Extract

# tar.xz (better compression)
tar -cJvf archive.tar.xz files
tar -xJvf archive.tar.xz

# zip
zip -r archive.zip directory
unzip archive.zip

# gzip single file
gzip file                   # Compresses in place
gunzip file.gz

Cron Jobs

# Edit crontab
crontab -e

# Format: minute hour day month weekday command
# *      *     *    *     *       command

# Examples:
# 0 5 * * * /path/script.sh          # Daily at 5am
# */15 * * * * /path/script.sh       # Every 15 minutes
# 0 0 * * 0 /path/script.sh          # Every Sunday at midnight
# 0 9-17 * * 1-5 /path/script.sh     # Hourly 9am-5pm weekdays

# List crontab
crontab -l

# System cron directories
/etc/cron.d/
/etc/cron.daily/
/etc/cron.hourly/
/etc/cron.weekly/
/etc/cron.monthly/

System Logs

# Systemd journal
journalctl                          # All logs
journalctl -f                       # Follow
journalctl --since "1 hour ago"
journalctl --since today
journalctl -p err                   # Errors only
journalctl -b                       # Since boot
journalctl -b -1                    # Previous boot

# Traditional logs (/var/log/)
/var/log/syslog                     # System log (Debian)
/var/log/messages                   # System log (RHEL)
/var/log/auth.log                   # Authentication
/var/log/kern.log                   # Kernel
/var/log/apt/                       # Package manager
/var/log/nginx/                     # Web server

Environment Variables

# View
echo $PATH
echo $HOME
printenv                    # All variables
env                         # All variables

# Set temporarily
export MYVAR="value"

# Set permanently (add to ~/.bashrc or ~/.profile)
export MYVAR="value"

# Path manipulation
export PATH="$PATH:/new/path"

Useful One-Liners

# Find large files
find / -type f -size +100M 2>/dev/null | head -20

# Find recently modified files
find /path -type f -mmin -60    # Last 60 minutes

# Disk usage by directory
du -h --max-depth=1 / 2>/dev/null | sort -h

# Count files in directory
find . -type f | wc -l

# Watch command output
watch -n 2 'df -h'              # Every 2 seconds

# History search
history | grep keyword
Ctrl+R                          # Interactive search

# Previous command tricks
!!                              # Repeat last command
sudo !!                         # Repeat with sudo
!$                              # Last argument of previous command

# Quick backup
cp file{,.bak}                  # Creates file.bak

# Download file
wget https://url/file
curl -O https://url/file

# Check open files by process
lsof -p PID
lsof -c process-name

# Memory hogs
ps aux --sort=-%mem | head -10

# CPU hogs
ps aux --sort=-%cpu | head -10

Maintenance Routine

Daily

# Check disk space
df -h

# Check for failed services
systemctl --failed

# Review recent logs for errors
journalctl -p err --since today

Weekly

# Update packages
sudo apt update && sudo apt upgrade

# Clean package cache
sudo apt autoremove
sudo apt autoclean

# Check for security updates
sudo apt list --upgradable

Monthly

# Full system backup (example with rsync)
sudo rsync -aAXv --exclude={"/dev/*","/proc/*","/sys/*","/tmp/*","/run/*","/mnt/*","/media/*","/lost+found"} / /backup/

# Review disk usage
ncdu /

# Check SMART status of drives
sudo smartctl -a /dev/sda

# Review user accounts
cat /etc/passwd | grep -v nologin

# Check listening ports
ss -tuln

Troubleshooting Checklist

  1. System won't boot

    • Check GRUB menu for recovery mode
    • Boot from live USB, mount drive, check logs
  2. Out of disk space

    • df -h to identify full partitions
    • du -sh /* | sort -h to find large directories
    • Clear package cache, logs, temp files
  3. Service not starting

    • systemctl status service-name
    • journalctl -u service-name -n 50
    • Check config file syntax
  4. Network not working

    • ip addr - check interface status
    • ping 8.8.8.8 - test connectivity
    • ping google.com - test DNS
    • Check firewall rules
  5. High CPU/memory usage

    • htop or top to identify process
    • Check if it's a runaway process or normal load
    • systemctl restart service-name if needed