Essential Linux Commands for System Administrators

Mastering essential Linux commands is fundamental to effective system administration. Whether you're troubleshooting server issues, managing users and permissions, monitoring system resources, or automating tasks, the Linux command line provides powerful tools that enable efficient server management and rapid problem resolution.

This comprehensive guide covers the most critical Linux commands every system administrator must know, organized by functional categories with practical examples, real-world use cases, and best practices. From file manipulation and process management to network diagnostics and security auditing, you'll learn the commands that form the foundation of professional Linux administration.

Table of Contents

  • Introduction
  • File and Directory Management
  • Text Processing and Manipulation
  • User and Permission Management
  • Process and Service Management
  • System Monitoring and Performance
  • Network Management and Troubleshooting
  • Disk and Filesystem Operations
  • Package Management
  • System Information and Logs
  • Security and Auditing
  • Compression and Archives
  • Remote Access and File Transfer
  • Advanced Command Techniques
  • Conclusion

Introduction

Linux system administration relies heavily on command-line proficiency. While graphical interfaces exist, the command line offers:

  • Speed: Execute complex operations in seconds
  • Automation: Script repetitive tasks for consistency
  • Remote Management: Administer servers over SSH without GUI overhead
  • Precision: Fine-grained control over system operations
  • Universality: Commands work across distributions and versions
  • Troubleshooting Power: Access system internals when GUIs fail

This guide assumes basic Linux familiarity but explains each command thoroughly with practical examples. Commands are organized by functional category, making this guide both a learning resource and a quick reference for daily administration tasks.

Environment Notes:

# Most commands require appropriate permissions
# Use sudo for administrative operations
sudo command-name

# Check manual pages for detailed information
man command-name

# Get quick help
command-name --help

File and Directory Management

File operations are fundamental to system administration.

ls - List Directory Contents

# Basic listing
ls

# Long format with detailed information
ls -l

# Show hidden files (starting with .)
ls -a

# Human-readable file sizes
ls -lh

# Sort by modification time (newest first)
ls -lt

# Recursive listing
ls -R

# Comprehensive listing (commonly used)
ls -lah

# Sort by size
ls -lhS

# Show inode numbers
ls -i

# Color-coded output (usually default)
ls --color=auto

Practical Examples:

# Find largest files in current directory
ls -lhS | head -10

# List only directories
ls -d */

# List files modified in last 24 hours
ls -lt | head -10

# Count files in directory
ls -1 | wc -l

# List files with specific extension
ls *.log

cd - Change Directory

# Change to specific directory
cd /var/log

# Change to home directory
cd ~
cd  # no arguments also goes home

# Go back to previous directory
cd -

# Move up one directory level
cd ..

# Move up two levels
cd ../..

# Change to subdirectory
cd ./subdirectory

pwd - Print Working Directory

# Show current directory
pwd

# Output: /home/username/projects

# Useful in scripts to verify location
CURRENT_DIR=$(pwd)
echo "Working in: $CURRENT_DIR"

mkdir - Make Directories

# Create single directory
mkdir newdir

# Create nested directories
mkdir -p /var/www/site/public/images

# Create with specific permissions
mkdir -m 755 publicdir

# Create multiple directories
mkdir dir1 dir2 dir3

# Verbose output
mkdir -v testdir

rm - Remove Files and Directories

# Remove file
rm file.txt

# Remove directory and contents recursively
rm -r directory/

# Force removal without confirmation
rm -f file.txt

# Combine recursive and force
rm -rf directory/

# Interactive confirmation
rm -i file.txt

# Remove multiple files
rm file1.txt file2.txt file3.txt

# Remove files by pattern
rm *.log

# Verbose output
rm -v file.txt

CAUTION:

# NEVER run these commands
# rm -rf / (destroys entire system)
# rm -rf /* (destroys all filesystems)

# Safe practice: use absolute paths and verify
ls /path/to/delete/  # verify first
rm -rf /path/to/delete/

cp - Copy Files and Directories

# Copy file
cp source.txt destination.txt

# Copy directory recursively
cp -r sourcedir/ destdir/

# Preserve attributes (permissions, timestamps)
cp -p file.txt backup.txt

# Comprehensive copy (archive mode)
cp -a sourcedir/ backup/

# Interactive confirmation before overwrite
cp -i source.txt dest.txt

# Verbose output
cp -v file.txt /backup/

# Copy multiple files to directory
cp file1.txt file2.txt /destination/

# Update only newer files
cp -u *.txt /backup/

mv - Move or Rename

# Rename file
mv oldname.txt newname.txt

# Move file to directory
mv file.txt /destination/

# Move multiple files
mv file1.txt file2.txt /destination/

# Move directory
mv olddir/ newdir/

# Interactive confirmation
mv -i source.txt dest.txt

# Don't overwrite existing files
mv -n file.txt /destination/

# Verbose output
mv -v file.txt newlocation/

find - Search for Files

# Find files by name
find /var/log -name "*.log"

# Case-insensitive search
find /home -iname "readme.txt"

# Find directories only
find /var -type d -name "cache"

# Find files only
find /etc -type f -name "*.conf"

# Find files modified in last 7 days
find /var/log -mtime -7

# Find files larger than 100MB
find /var -size +100M

# Find and execute command on results
find /tmp -type f -mtime +7 -exec rm {} \;

# Find with permissions
find /var/www -type f -perm 0777

# Find files owned by user
find /home -user username

# Find and list details
find /etc -name "*.conf" -ls

Advanced Examples:

# Find and delete old log files
find /var/log -name "*.log" -mtime +30 -delete

# Find large files and show sizes
find /var -size +500M -exec ls -lh {} \; | awk '{print $9, $5}'

# Find files and copy to backup
find /etc -name "*.conf" -exec cp {} /backup/ \;

chmod - Change Permissions

# Add execute permission for user
chmod u+x script.sh

# Remove write permission for group
chmod g-w file.txt

# Set specific permissions (rwxr-xr-x = 755)
chmod 755 script.sh

# Recursive permission change
chmod -R 755 /var/www/

# Make file readable by all
chmod a+r file.txt

# Symbolic permissions
chmod u=rwx,g=rx,o=r file.txt

# Set directory permissions
chmod 755 directory/

Common Permission Values:

# 644 = rw-r--r-- (files)
chmod 644 file.txt

# 755 = rwxr-xr-x (executables, directories)
chmod 755 script.sh

# 600 = rw------- (private files)
chmod 600 ~/.ssh/id_rsa

# 700 = rwx------ (private directories)
chmod 700 ~/private/

chown - Change Ownership

# Change owner
chown username file.txt

# Change owner and group
chown username:groupname file.txt

# Recursive ownership change
chown -R www-data:www-data /var/www/

# Change group only
chown :groupname file.txt
# or use chgrp
chgrp groupname file.txt

Text Processing and Manipulation

Text processing is essential for log analysis and configuration management.

cat - Concatenate and Display Files

# Display file contents
cat file.txt

# Display multiple files
cat file1.txt file2.txt

# Number all lines
cat -n file.txt

# Number non-blank lines
cat -b file.txt

# Show end of line markers
cat -E file.txt

# Concatenate files into new file
cat file1.txt file2.txt > combined.txt

# Append to file
cat additional.txt >> existing.txt

grep - Search Text Patterns

# Search for pattern in file
grep "error" /var/log/syslog

# Case-insensitive search
grep -i "error" logfile.txt

# Recursive search in directories
grep -r "error" /var/log/

# Show line numbers
grep -n "error" file.txt

# Count matching lines
grep -c "error" file.txt

# Invert match (show non-matching lines)
grep -v "debug" file.txt

# Show context (3 lines before and after)
grep -C 3 "error" file.txt

# Show only filenames with matches
grep -l "error" /var/log/*

# Regular expression search
grep -E "error|warning" file.txt

# Search multiple patterns from file
grep -f patterns.txt logfile.txt

Practical Examples:

# Find all error messages in logs
grep -i "error" /var/log/syslog | tail -20

# Count 404 errors in Apache log
grep "404" /var/log/apache2/access.log | wc -l

# Find failed login attempts
grep "Failed password" /var/log/auth.log

# Search for IP address pattern
grep -E "([0-9]{1,3}\.){3}[0-9]{1,3}" file.txt

# Find processes by name
ps aux | grep nginx

sed - Stream Editor

# Replace first occurrence on each line
sed 's/old/new/' file.txt

# Replace all occurrences
sed 's/old/new/g' file.txt

# Edit file in place
sed -i 's/old/new/g' file.txt

# Delete lines containing pattern
sed '/pattern/d' file.txt

# Print specific line numbers
sed -n '10,20p' file.txt

# Delete blank lines
sed '/^$/d' file.txt

# Insert text before pattern
sed '/pattern/i\New line here' file.txt

# Append text after pattern
sed '/pattern/a\New line here' file.txt

Practical Examples:

# Change IP address in configuration
sed -i 's/192.168.1.10/192.168.1.20/g' /etc/hosts

# Comment out lines matching pattern
sed -i '/DEBUG/s/^/#/' config.conf

# Remove comments from configuration
sed '/^#/d' /etc/ssh/sshd_config

# Replace multiple spaces with single space
sed 's/  */ /g' file.txt

awk - Text Processing Language

# Print specific columns
awk '{print $1, $3}' file.txt

# Print lines longer than 80 characters
awk 'length > 80' file.txt

# Sum numbers in column
awk '{sum += $1} END {print sum}' numbers.txt

# Print with custom delimiter
awk -F: '{print $1, $3}' /etc/passwd

# Conditional processing
awk '$3 > 100 {print $1}' file.txt

# Format output
awk '{printf "%-10s %s\n", $1, $2}' file.txt

# Calculate and print
awk '{print $1, $2, $1+$2}' file.txt

Practical Examples:

# List users with UID >= 1000
awk -F: '$3 >= 1000 {print $1}' /etc/passwd

# Calculate total disk usage
df -h | awk '{sum += $3} END {print sum}'

# Print unique values
awk '!seen[$1]++' file.txt

# Apache log analysis - count requests per IP
awk '{print $1}' /var/log/apache2/access.log | sort | uniq -c | sort -rn

head and tail - View File Portions

# Show first 10 lines (default)
head file.txt

# Show first N lines
head -n 20 file.txt

# Show first N bytes
head -c 100 file.txt

# Show last 10 lines (default)
tail file.txt

# Show last N lines
tail -n 50 file.txt

# Follow file updates (log monitoring)
tail -f /var/log/syslog

# Follow multiple files
tail -f /var/log/syslog /var/log/auth.log

# Show last N lines and follow
tail -n 100 -f /var/log/apache2/access.log

wc - Word Count

# Count lines, words, characters
wc file.txt

# Count lines only
wc -l file.txt

# Count words only
wc -w file.txt

# Count characters
wc -c file.txt

# Count lines in multiple files
wc -l *.txt

Practical Examples:

# Count files in directory
ls | wc -l

# Count users on system
cat /etc/passwd | wc -l

# Count error occurrences
grep -i "error" /var/log/syslog | wc -l

User and Permission Management

Managing users and permissions is critical for system security.

useradd - Create User

# Create basic user
sudo useradd username

# Create user with home directory
sudo useradd -m username

# Create with specific shell
sudo useradd -s /bin/bash username

# Create with specific UID
sudo useradd -u 1500 username

# Create with specific group
sudo useradd -g groupname username

# Create with multiple groups
sudo useradd -G group1,group2 username

# Create system user
sudo useradd -r serviceuser

# Comprehensive user creation
sudo useradd -m -s /bin/bash -G sudo,docker username

usermod - Modify User

# Add user to group
sudo usermod -aG groupname username

# Change user's shell
sudo usermod -s /bin/zsh username

# Change user's home directory
sudo usermod -d /new/home username

# Lock user account
sudo usermod -L username

# Unlock user account
sudo usermod -U username

# Change username
sudo usermod -l newname oldname

passwd - Change Password

# Change your own password
passwd

# Change another user's password (as root)
sudo passwd username

# Force password change on next login
sudo passwd -e username

# Lock account
sudo passwd -l username

# Unlock account
sudo passwd -u username

# Set password expiry
sudo passwd -x 90 username

groupadd and groupmod - Group Management

# Create group
sudo groupadd developers

# Create with specific GID
sudo groupadd -g 2000 developers

# Delete group
sudo groupdel groupname

# Rename group
sudo groupmod -n newname oldname

# Change GID
sudo groupmod -g 3000 groupname

id - Display User Information

# Show current user ID and groups
id

# Show specific user information
id username

# Show only UID
id -u

# Show only GID
id -g

# Show all groups
id -G

# Show group names
id -Gn

su and sudo - Switch Users and Elevate Privileges

# Switch to root
su -

# Switch to specific user
su - username

# Execute command as root
sudo command

# Execute command as specific user
sudo -u username command

# Start root shell
sudo -i

# Edit file with elevated privileges
sudo nano /etc/hosts

# Execute previous command with sudo
sudo !!

Process and Service Management

Managing processes and services is fundamental to system administration.

ps - Process Status

# Show your processes
ps

# Show all processes (BSD style)
ps aux

# Show all processes (Unix style)
ps -ef

# Show process tree
ps auxf

# Show specific user's processes
ps -u username

# Sort by CPU usage
ps aux --sort=-%cpu | head -10

# Sort by memory usage
ps aux --sort=-%mem | head -10

# Show threads
ps -eLf

Practical Examples:

# Find process by name
ps aux | grep nginx

# Count processes
ps aux | wc -l

# Show full command line
ps auxww

# Monitor specific process
ps -p PID -o pid,cmd,%cpu,%mem

top and htop - Interactive Process Viewer

# Launch top
top

# Key commands within top:
# h - help
# k - kill process
# r - renice process
# M - sort by memory
# P - sort by CPU
# q - quit

# Show specific user's processes
top -u username

# Update every 2 seconds
top -d 2

# Batch mode (non-interactive)
top -b -n 1 > /tmp/top-output.txt

# htop (more user-friendly, install separately)
htop

# htop features:
# - Mouse support
# - Color coding
# - Tree view (F5)
# - Search (F3)
# - Filter (F4)

kill - Terminate Processes

# Graceful termination (SIGTERM)
kill PID

# Force termination (SIGKILL)
kill -9 PID

# Send specific signal
kill -SIGHUP PID

# Kill all processes by name
killall processname

# Kill all user's processes
killall -u username

# Kill with pattern matching
pkill -f "pattern"

# Interactive process selection and kill
top  # then press 'k' and enter PID

Common Signals:

# Signal list
kill -l

# Common signals:
# 1  HUP   - Hang up (reload configuration)
# 2  INT   - Interrupt (Ctrl+C)
# 9  KILL  - Force kill (cannot be caught)
# 15 TERM  - Graceful termination (default)
# 18 CONT  - Continue stopped process
# 19 STOP  - Stop process

systemctl - System and Service Manager

# Start service
sudo systemctl start nginx

# Stop service
sudo systemctl stop nginx

# Restart service
sudo systemctl restart nginx

# Reload configuration
sudo systemctl reload nginx

# Check service status
systemctl status nginx

# Enable service at boot
sudo systemctl enable nginx

# Disable service at boot
sudo systemctl disable nginx

# Check if service is enabled
systemctl is-enabled nginx

# Check if service is active
systemctl is-active nginx

# List all services
systemctl list-units --type=service

# List failed services
systemctl --failed

# View service logs
journalctl -u nginx.service

# Mask service (prevent starting)
sudo systemctl mask service-name

# Unmask service
sudo systemctl unmask service-name

journalctl - Query systemd Logs

# View all logs
journalctl

# View logs from current boot
journalctl -b

# View logs from previous boot
journalctl -b -1

# Follow logs in real-time
journalctl -f

# View logs for specific service
journalctl -u nginx.service

# View logs since time
journalctl --since "2024-01-01"
journalctl --since "1 hour ago"

# View logs with priority
journalctl -p err

# Reverse order (newest first)
journalctl -r

# Show kernel messages
journalctl -k

# Vacuum old logs
sudo journalctl --vacuum-time=7d
sudo journalctl --vacuum-size=1G

System Monitoring and Performance

Monitoring system resources prevents performance issues and aids troubleshooting.

df - Disk Filesystem Usage

# Show disk usage
df

# Human-readable sizes
df -h

# Show inode usage
df -i

# Show specific filesystem
df -h /var

# Show filesystem type
df -T

# Exclude specific filesystem types
df -x tmpfs -x devtmpfs

du - Disk Usage

# Show directory sizes
du /var

# Human-readable format
du -h /var/log

# Summary for directory
du -sh /var/log

# Show all files and directories
du -ah /var/log

# Show sizes sorted
du -ah /var/log | sort -rh | head -20

# Limit depth
du -h --max-depth=1 /var

# Exclude patterns
du -h --exclude="*.log" /var

free - Memory Usage

# Show memory usage
free

# Human-readable format
free -h

# Show in megabytes
free -m

# Show in gigabytes
free -g

# Continuous updates
free -h -s 2  # update every 2 seconds

# Show total line
free -h -t

uptime - System Uptime and Load

# Show uptime and load average
uptime

# Output:
# 15:23:42 up 30 days, 4:12, 2 users, load average: 0.50, 0.75, 0.80

# Load average explained:
# - 1 minute average
# - 5 minute average
# - 15 minute average
# Values relative to CPU core count

vmstat - Virtual Memory Statistics

# Show virtual memory stats
vmstat

# Update every 2 seconds
vmstat 2

# Show 10 updates, 2 seconds apart
vmstat 2 10

# Show in megabytes
vmstat -S M

# Detailed memory statistics
vmstat -s

# Disk statistics
vmstat -d

iostat - I/O Statistics

# Show CPU and I/O statistics
iostat

# Update every 2 seconds
iostat 2

# Extended statistics
iostat -x

# Show in megabytes
iostat -m

# Specific device
iostat -x sda

Network Management and Troubleshooting

Network commands are essential for connectivity troubleshooting and configuration.

ip - Network Configuration

# Show all network interfaces
ip addr show
ip a  # shorthand

# Show specific interface
ip addr show eth0

# Show routing table
ip route show
ip r  # shorthand

# Add IP address
sudo ip addr add 192.168.1.100/24 dev eth0

# Delete IP address
sudo ip addr del 192.168.1.100/24 dev eth0

# Bring interface up
sudo ip link set eth0 up

# Bring interface down
sudo ip link set eth0 down

# Show link status
ip link show

# Show network statistics
ip -s link show eth0

ping - Network Connectivity Test

# Ping host
ping google.com

# Limit to 5 packets
ping -c 5 google.com

# Set packet size
ping -s 1000 google.com

# Flood ping (root only, testing)
sudo ping -f localhost

# Set interval
ping -i 2 google.com  # ping every 2 seconds

# IPv6 ping
ping6 ipv6.google.com

netstat - Network Statistics

# Show all connections
netstat -a

# Show listening ports
netstat -l

# Show TCP connections
netstat -t

# Show UDP connections
netstat -u

# Show with program names
sudo netstat -p

# Show routing table
netstat -r

# Common combination (listening TCP with programs)
sudo netstat -tlnp

# Show network statistics
netstat -s

# Continuous monitoring
netstat -c

ss - Socket Statistics (modern netstat replacement)

# Show all sockets
ss -a

# Show listening sockets
ss -l

# Show TCP sockets
ss -t

# Show UDP sockets
ss -u

# Show process using socket
ss -p

# Show summary statistics
ss -s

# Common combination
ss -tlnp  # TCP, listening, numeric, process

# Show specific port
ss -tlnp | grep :80

# Show socket memory
ss -m

nslookup and dig - DNS Lookup

# Basic DNS lookup
nslookup google.com

# Query specific DNS server
nslookup google.com 8.8.8.8

# Reverse lookup
nslookup 8.8.8.8

# dig (more detailed)
dig google.com

# Short answer only
dig +short google.com

# Query specific record type
dig google.com MX
dig google.com TXT

# Trace DNS resolution
dig +trace google.com

# Query specific DNS server
dig @8.8.8.8 google.com

# Reverse DNS lookup
dig -x 8.8.8.8

traceroute - Trace Network Path

# Trace route to host
traceroute google.com

# Use ICMP instead of UDP
sudo traceroute -I google.com

# Limit hops
traceroute -m 15 google.com

# Don't resolve hostnames
traceroute -n google.com

curl and wget - Download Files and Test HTTP

# Download file with curl
curl -O https://example.com/file.txt

# Save with different name
curl -o newname.txt https://example.com/file.txt

# Follow redirects
curl -L https://example.com

# Show headers only
curl -I https://example.com

# POST request
curl -X POST -d "param=value" https://api.example.com

# Download with wget
wget https://example.com/file.txt

# Download in background
wget -b https://example.com/largefile.iso

# Resume partial download
wget -c https://example.com/file.txt

# Mirror website
wget -m https://example.com

Disk and Filesystem Operations

Managing disks and filesystems is crucial for storage administration.

mount and umount - Mount Filesystems

# Show mounted filesystems
mount

# Mount filesystem
sudo mount /dev/sdb1 /mnt

# Mount with specific filesystem type
sudo mount -t ext4 /dev/sdb1 /mnt

# Mount with options
sudo mount -o ro,noexec /dev/sdb1 /mnt

# Unmount filesystem
sudo umount /mnt

# Force unmount
sudo umount -f /mnt

# Lazy unmount
sudo umount -l /mnt

# Remount with different options
sudo mount -o remount,rw /mnt

fdisk - Partition Management

# List disks
sudo fdisk -l

# Start fdisk on specific disk
sudo fdisk /dev/sdb

# Within fdisk:
# m - help menu
# p - print partition table
# n - new partition
# d - delete partition
# w - write changes
# q - quit without saving

# Show disk size
sudo fdisk -s /dev/sdb

lsblk - List Block Devices

# List all block devices
lsblk

# Show filesystem type
lsblk -f

# Show size in bytes
lsblk -b

# Show specific device
lsblk /dev/sda

# Show permissions
lsblk -m

mkfs - Create Filesystem

# Create ext4 filesystem
sudo mkfs.ext4 /dev/sdb1

# Create XFS filesystem
sudo mkfs.xfs /dev/sdb1

# Create with label
sudo mkfs.ext4 -L "DataDisk" /dev/sdb1

# Create with specific options
sudo mkfs.ext4 -m 1 -O ^has_journal /dev/sdb1

Package Management

Package management varies by distribution but follows similar patterns.

APT (Debian/Ubuntu)

# Update package list
sudo apt update

# Upgrade all packages
sudo apt upgrade

# Full upgrade (handle dependencies)
sudo apt full-upgrade

# Install package
sudo apt install nginx

# Remove package
sudo apt remove nginx

# Remove with configuration
sudo apt purge nginx

# Search for package
apt search nginx

# Show package information
apt show nginx

# List installed packages
apt list --installed

# Clean cache
sudo apt clean
sudo apt autoclean

# Remove unused dependencies
sudo apt autoremove

YUM/DNF (Red Hat/CentOS/Rocky)

# Check for updates
dnf check-update

# Update all packages
sudo dnf update

# Install package
sudo dnf install nginx

# Remove package
sudo dnf remove nginx

# Search package
dnf search nginx

# Show package info
dnf info nginx

# List installed packages
dnf list installed

# Clean cache
sudo dnf clean all

# Remove unused dependencies
sudo dnf autoremove

# List repositories
dnf repolist

# Enable repository
sudo dnf config-manager --enable repo-name

System Information and Logs

Gathering system information aids troubleshooting and documentation.

uname - System Information

# Show all information
uname -a

# Show kernel name
uname -s

# Show kernel release
uname -r

# Show kernel version
uname -v

# Show machine hardware
uname -m

# Show processor type
uname -p

# Show operating system
uname -o

hostname and hostnamectl - Host Information

# Show hostname
hostname

# Set hostname (temporary)
sudo hostname newhostname

# Show FQDN
hostname -f

# Show IP address
hostname -I

# Using hostnamectl (systemd systems)
hostnamectl

# Set hostname permanently
sudo hostnamectl set-hostname newhostname

# Set with all details
sudo hostnamectl set-hostname newhostname --static

dmesg - Kernel Messages

# Show all kernel messages
dmesg

# Show with human-readable timestamps
dmesg -T

# Follow new messages
dmesg -w

# Show error and warning messages
dmesg -level=err,warn

# Clear kernel ring buffer
sudo dmesg -C

# Show last 50 messages
dmesg | tail -50

last and who - Login History

# Show login history
last

# Show last 10 logins
last -10

# Show last logins for user
last username

# Show last reboot
last reboot

# Show currently logged in users
who

# Show current user
whoami

# Show detailed user info
who -a

# Show login time
who -b

Security and Auditing

Security commands help monitor and maintain system security.

iptables - Firewall Rules

# List all rules
sudo iptables -L

# List with line numbers
sudo iptables -L --line-numbers

# List specific chain
sudo iptables -L INPUT

# Add rule to allow port
sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT

# Delete rule by number
sudo iptables -D INPUT 5

# Flush all rules
sudo iptables -F

# Save rules
sudo iptables-save > /etc/iptables/rules.v4

# Restore rules
sudo iptables-restore < /etc/iptables/rules.v4

firewalld - Firewall Management

# Check status
sudo firewall-cmd --state

# List all zones
sudo firewall-cmd --get-zones

# List active zones
sudo firewall-cmd --get-active-zones

# List all rules
sudo firewall-cmd --list-all

# Add port
sudo firewall-cmd --permanent --add-port=80/tcp

# Add service
sudo firewall-cmd --permanent --add-service=http

# Remove port
sudo firewall-cmd --permanent --remove-port=80/tcp

# Reload firewall
sudo firewall-cmd --reload

ssh - Secure Shell

# Connect to remote host
ssh user@hostname

# Use specific port
ssh -p 2222 user@hostname

# Use specific identity file
ssh -i ~/.ssh/id_rsa user@hostname

# Execute remote command
ssh user@hostname 'uptime'

# Port forwarding
ssh -L 8080:localhost:80 user@hostname

# Generate SSH key
ssh-keygen -t rsa -b 4096

# Copy SSH key to remote
ssh-copy-id user@hostname

Compression and Archives

Compression and archiving for backups and file transfer.

tar - Archive Files

# Create archive
tar -cf archive.tar files/

# Create compressed archive (gzip)
tar -czf archive.tar.gz files/

# Create compressed archive (bzip2)
tar -cjf archive.tar.bz2 files/

# Extract archive
tar -xf archive.tar

# Extract gzip archive
tar -xzf archive.tar.gz

# List archive contents
tar -tf archive.tar

# Extract to specific directory
tar -xzf archive.tar.gz -C /destination/

# Verbose output
tar -xzvf archive.tar.gz

gzip, bzip2, xz - Compression

# Compress file (removes original)
gzip file.txt

# Decompress
gunzip file.txt.gz

# Keep original file
gzip -k file.txt

# Compress with bzip2
bzip2 file.txt

# Decompress bzip2
bunzip2 file.txt.bz2

# Compress with xz (best compression)
xz file.txt

# Decompress xz
unxz file.txt.xz

Advanced Command Techniques

Combining commands and advanced techniques for powerful automation.

Pipes and Redirection

# Pipe output to another command
ps aux | grep nginx

# Redirect output to file (overwrite)
echo "text" > file.txt

# Redirect output (append)
echo "more text" >> file.txt

# Redirect stderr to file
command 2> error.log

# Redirect both stdout and stderr
command > output.log 2>&1

# Redirect stderr to stdout
command 2>&1 | grep "error"

# Pipe to multiple commands
ps aux | grep nginx | awk '{print $2}'

Command Substitution

# Use command output as argument
echo "Today is $(date)"

# Assign command output to variable
FILES=$(ls /var/log)

# Nested substitution
echo "Logged in users: $(who | wc -l)"

Background and Job Control

# Run command in background
command &

# List background jobs
jobs

# Bring job to foreground
fg %1

# Send job to background
bg %1

# Disown job
disown %1

# Run command ignoring hangup
nohup command &

Aliases and Functions

# Create alias
alias ll='ls -lah'

# Remove alias
unalias ll

# List aliases
alias

# Make permanent (add to ~/.bashrc)
echo "alias ll='ls -lah'" >> ~/.bashrc

# Create function
function backup() {
    tar -czf "backup-$(date +%Y%m%d).tar.gz" "$@"
}

Conclusion

Mastering these essential Linux commands transforms system administration from reactive troubleshooting to proactive management. The commands covered in this guide form the foundation of professional Linux administration, enabling efficient server management, rapid problem resolution, and powerful automation capabilities.

Key Takeaways:

  1. Command Proficiency: Practice commands regularly in non-production environments before using them on live systems.

  2. Man Pages: Use man command-name to access comprehensive documentation for any command.

  3. Safety First: Always verify commands before execution, especially with rm, dd, and other destructive operations.

  4. Combine Commands: Pipes, redirects, and command substitution create powerful one-liners from simple commands.

  5. Automate: Convert frequently used command sequences into scripts for consistency and efficiency.

  6. Log Review: Regular log analysis with grep, awk, and journalctl identifies issues before they become critical.

  7. System Monitoring: Proactive monitoring with top, df, free, and netstat prevents resource exhaustion.

Recommended Learning Path:

  1. Beginner: Focus on file management, text viewing, and basic system information
  2. Intermediate: Add user management, process control, and network commands
  3. Advanced: Master text processing, automation, and complex command combinations
  4. Expert: Create comprehensive scripts combining multiple commands for complex workflows

Best Practices:

  • Always use absolute paths in scripts
  • Verify commands with non-destructive flags first (-n for dry run where available)
  • Document complex command sequences
  • Use version control for scripts
  • Test on non-production systems
  • Keep backups before making system changes
  • Review man pages and help output regularly

Daily Command Reference:

# System health check one-liner
uptime && free -h && df -h / && systemctl --failed

# Find largest files
du -ah / 2>/dev/null | sort -rh | head -20

# Network connectivity test
ping -c 3 8.8.8.8 && curl -I https://google.com

# Security audit
last | head -10 && sudo grep "Failed" /var/log/auth.log | tail -10

The Linux command line is extraordinarily powerful. Commands that might require multiple GUI clicks and minutes of navigation execute in seconds from the terminal. This speed advantage multiplies when managing multiple servers or automating routine tasks.

Continue practicing these commands, explore their man pages for additional options, and gradually build muscle memory for common operations. The investment in command-line proficiency pays dividends throughout your career as a system administrator.

Next Steps

  1. Create a personal command reference document
  2. Practice commands in a test environment daily
  3. Build a collection of useful scripts
  4. Join Linux communities and forums
  5. Contribute to open-source projects
  6. Pursue Linux certifications (LFCS, RHCSA)
  7. Read system administration blogs and tutorials

The commands in this guide represent the foundation. As you grow in experience, you'll discover specialized tools for specific tasks, but these essential commands will remain central to your daily work as a Linux system administrator.