Skip to main content

Linux Commands Guide

A comprehensive reference guide for essential Linux commands with practical examples and use cases.

Table of Contents


File and Directory Operations

ls - List Directory Contents

# Basic listing
ls

# Detailed listing with permissions, ownership, size
ls -la

# List only directories
ls -d */

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

# Human-readable file sizes
ls -lh

find - Search for Files and Directories

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

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

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

# Find and execute command on results
find /tmp -name "*.tmp" -delete

# Find files with specific permissions
find /etc -perm 644

cp - Copy Files and Directories

# Copy file
cp source.txt destination.txt

# Copy directory recursively
cp -r /source/directory /destination/

# Preserve permissions and timestamps
cp -p file1.txt file2.txt

# Copy with verbose output
cp -v *.txt /backup/

rsync - Synchronize Files/Directories

# Sync directories locally
rsync -av /source/ /destination/

# Sync to remote server
rsync -av /local/path/ user@server:/remote/path/

# Sync with compression and progress
rsync -avz --progress /source/ user@server:/dest/

# Dry run (test without actually copying)
rsync -av --dry-run /source/ /dest/

Text Processing

grep - Search Text Patterns

# Basic search
grep "error" /var/log/messages

# Case-insensitive search
grep -i "warning" /var/log/syslog

# Search recursively in directories
grep -r "configuration" /etc/

# Show line numbers
grep -n "failed" /var/log/auth.log

# Search for whole words only
grep -w "root" /etc/passwd

# Invert match (show lines that don't match)
grep -v "DEBUG" /var/log/application.log

sed - Stream Editor

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

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

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

# Print only lines 10-20
sed -n '10,20p' file.txt

# In-place editing
sed -i 's/old/new/g' file.txt

awk - Text Processing Tool

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

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

# Sum values in column 3
awk '{sum += $3} END {print sum}' file.txt

# Process CSV files
awk -F',' '{print $2}' data.csv

# Print lines matching pattern
awk '/pattern/ {print}' file.txt

System Information

ps - Process Status

# Show all processes
ps aux

# Show process tree
ps aux --forest

# Show processes for specific user
ps -u username

# Show processes by CPU usage
ps aux --sort=-%cpu

# Show specific process
ps aux | grep nginx

top / htop - Real-time Process Viewer

# Basic top command
top

# Sort by memory usage
top -o %MEM

# Show specific user's processes
top -u username

# htop (if installed) - more user-friendly
htop

df - Disk Space Usage

# Show disk usage
df -h

# Show inodes usage
df -i

# Show specific filesystem type
df -t ext4

du - Directory Space Usage

# Show directory sizes
du -h /var/log/

# Show total size only
du -sh /home/user/

# Show largest directories
du -h /var/ | sort -hr | head -10

Process Management

kill - Terminate Processes

# Kill process by PID
kill 1234

# Force kill process
kill -9 1234

# Kill process by name
killall nginx

# Send specific signal
kill -HUP 1234

nohup - Run Commands Immune to Hangups

# Run command in background
nohup ./long-running-script.sh &

# Run with output redirection
nohup python app.py > app.log 2>&1 &

jobs - Job Control

# List active jobs
jobs

# Bring job to foreground
fg %1

# Send job to background
bg %1

# Start process in background
./script.sh &

Network Commands

netstat - Network Statistics

# Show all listening ports
netstat -tuln

# Show active connections
netstat -tu

# Show process using ports
netstat -tulnp

# Show routing table
netstat -rn

ss - Socket Statistics (modern netstat)

# Show listening ports
ss -tuln

# Show established connections
ss -tu state established

# Show processes using ports
ss -tulnp

ping - Network Connectivity Test

# Basic ping
ping google.com

# Ping with count
ping -c 4 8.8.8.8

# Ping with interval
ping -i 2 192.168.1.1

curl - Transfer Data

# Basic GET request
curl https://api.example.com

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

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

# Follow redirects
curl -L https://short.url

# Include response headers
curl -I https://example.com

File Permissions and Ownership

chmod - Change File Permissions

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

# Add execute permission
chmod +x file.sh

# Remove write permission for group and others
chmod go-w file.txt

# Recursive permission change
chmod -R 644 /var/www/html/

chown - Change File Ownership

# Change owner
chown user file.txt

# Change owner and group
chown user:group file.txt

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

umask - Set Default Permissions

# Show current umask
umask

# Set umask (files: 644, dirs: 755)
umask 022

Archive and Compression

tar - Archive Files

# Create archive
tar -czf backup.tar.gz /home/user/

# Extract archive
tar -xzf backup.tar.gz

# List archive contents
tar -tzf backup.tar.gz

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

# Create archive with verbose output
tar -czvf backup.tar.gz /data/

zip / unzip - ZIP Archives

# Create zip archive
zip -r backup.zip /home/user/

# Extract zip archive
unzip backup.zip

# List zip contents
unzip -l backup.zip

# Extract to specific directory
unzip backup.zip -d /destination/

System Monitoring

iostat - I/O Statistics

# Show I/O statistics
iostat

# Update every 2 seconds
iostat 2

# Show extended statistics
iostat -x

vmstat - Virtual Memory Statistics

# Show memory and CPU statistics
vmstat

# Update every 2 seconds, 5 times
vmstat 2 5

sar - System Activity Reporter

# CPU utilization
sar -u

# Memory utilization
sar -r

# Network statistics
sar -n DEV

# Historical data
sar -u -f /var/log/sa/sa01

Service Management

systemctl - SystemD Service Control

# Start service
systemctl start nginx

# Stop service
systemctl stop nginx

# Restart service
systemctl restart nginx

# Enable service at boot
systemctl enable nginx

# Check service status
systemctl status nginx

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

Service Logs

# View service logs
journalctl -u nginx

# Follow service logs
journalctl -u nginx -f

# Show logs since yesterday
journalctl -u nginx --since yesterday

Log Analysis

tail - View End of Files

# Show last 10 lines
tail /var/log/messages

# Show last 50 lines
tail -n 50 /var/log/syslog

# Follow log file (real-time)
tail -f /var/log/nginx/access.log

# Follow multiple files
tail -f /var/log/*.log

head - View Beginning of Files

# Show first 10 lines
head /var/log/messages

# Show first 20 lines
head -n 20 /var/log/syslog

Log Rotation with logrotate

# Test logrotate configuration
logrotate -d /etc/logrotate.conf

# Force log rotation
logrotate -f /etc/logrotate.conf

Advanced Tips and Tricks

Command Chaining

# Run command only if previous succeeds
command1 && command2

# Run command only if previous fails
command1 || command2

# Chain multiple commands
command1; command2; command3

Input/Output Redirection

# Redirect output to file
command > output.txt

# Append to file
command >> output.txt

# Redirect error to file
command 2> error.log

# Redirect both output and error
command > output.txt 2>&1

Useful Aliases

# Add to ~/.bashrc
alias ll='ls -la'
alias la='ls -A'
alias l='ls -CF'
alias grep='grep --color=auto'
alias df='df -h'
alias free='free -h'

Security Commands

sudo - Execute as Another User

# Run command as root
sudo command

# Run command as specific user
sudo -u username command

# Switch to root shell
sudo -i

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

passwd - Change Password

# Change own password
passwd

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

Quick Reference Card

CommandDescriptionExample
ls -laList files with detailsls -la /etc/
findSearch filesfind /var -name "*.log"
grep -rSearch in filesgrep -r "error" /var/log/
ps auxShow processesps aux | grep nginx
df -hDisk usagedf -h
topProcess monitortop
tail -fFollow logtail -f /var/log/messages
systemctlService controlsystemctl status nginx
chmodChange permissionschmod 755 script.sh
tar -czfCreate archivetar -czf backup.tar.gz /data/

Remember: Always test commands in a safe environment before using them in production. Use man command to get detailed information about any command.

Pro Tip: Use history command to see your recent commands, and !! to repeat the last command with sudo (e.g., sudo !!).