Linux & Bash Commands Cheatsheet

Essential Command Line Reference for Linux and macOS

Category: Systems / Cybersecurity / DevOps
Level: Beginner — Intermediate

Essential Linux and Bash commands cheatsheet for developers, cybersecurity professionals, and sysadmins. Navigation, file management, permissions, processes, networking, and text processing.

# Show current directory
pwd

# Change directory
cd /path/to/directory
cd ~              # Home directory
cd -              # Previous directory
cd ..             # Parent directory
cd ../..          # Two levels up

# List directory contents
ls                # Basic list
ls -l             # Long format (permissions, size, date)
ls -a             # Include hidden files (starting with .)
ls -la            # Long format + hidden files
ls -lh            # Human-readable file sizes
ls -lt            # Sort by modification time (newest first)
ls -lS            # Sort by file size (largest first)
ls -R             # Recursive listing

# Show directory tree structure
tree
tree -L 2         # Limit depth to 2 levels
tree -a           # Include hidden files

📂 File & Directory Operations

# Create files
touch file.txt             # Create empty file or update timestamp
touch file1.txt file2.txt  # Create multiple files

# Create directories
mkdir my-folder
mkdir -p path/to/nested/folder  # Create nested (no error if exists)

# Copy
cp source.txt destination.txt
cp -r source-dir/ dest-dir/    # Copy directory recursively
cp -p file.txt backup.txt      # Preserve permissions and timestamps

# Move / Rename
mv old-name.txt new-name.txt
mv file.txt /path/to/destination/
mv -i file.txt dest.txt        # Prompt before overwrite

# Delete
rm file.txt
rm -f file.txt                 # Force (no confirmation)
rm -r directory/               # Remove directory recursively
rm -rf directory/              # Force remove directory (dangerous!)

# Remove empty directory
rmdir empty-folder

# View file contents
cat file.txt                   # Print entire file
cat -n file.txt                # With line numbers
less file.txt                  # Paginated view (q to quit)
more file.txt                  # Basic paginated view
head file.txt                  # First 10 lines
head -n 20 file.txt            # First 20 lines
tail file.txt                  # Last 10 lines
tail -n 50 file.txt            # Last 50 lines
tail -f logfile.log            # Follow file (live updates)

# File information
file document.pdf              # Determine file type
stat file.txt                  # Detailed file metadata
wc file.txt                    # Word, line, character count
wc -l file.txt                 # Line count only

# Find files
find . -name "*.txt"                    # Find by name
find . -name "*.log" -type f           # Files only
find /home -user alice                 # Files owned by user
find . -size +10M                      # Files larger than 10MB
find . -mtime -7                       # Modified in last 7 days
find . -name "*.tmp" -delete           # Find and delete

# Locate (uses a database — faster than find)
locate filename.txt
sudo updatedb                          # Update locate database

🔐 Permissions

# View permissions
ls -l file.txt
# Output: -rwxr-xr-- 1 alice staff 1024 Jan 15 10:00 file.txt
# Format: [type][owner][group][others]
# - = file, d = directory, l = symlink
# r = read(4), w = write(2), x = execute(1)

# Change permissions (numeric)
chmod 755 file.sh    # rwxr-xr-x (owner: full, group/others: read+execute)
chmod 644 file.txt   # rw-r--r-- (owner: read+write, others: read only)
chmod 600 secret.key # rw------- (owner only: read+write)
chmod 777 script.sh  # rwxrwxrwx (everyone: full — avoid in production)

# Change permissions (symbolic)
chmod +x script.sh            # Add execute for all
chmod u+x script.sh           # Add execute for owner only
chmod g-w file.txt            # Remove write from group
chmod o-r private.txt         # Remove read from others
chmod u=rwx,g=rx,o= file.sh  # Set exact permissions

# Recursive permissions
chmod -R 755 directory/

# Change owner
chown alice file.txt
chown alice:staff file.txt    # Owner and group
chown -R alice:staff dir/     # Recursive

# Change group
chgrp staff file.txt

# Common permission patterns
chmod 700  # rwx------ Owner only access
chmod 755  # rwxr-xr-x Standard executable/directory
chmod 644  # rw-r--r-- Standard file
chmod 600  # rw------- Private files (SSH keys, etc.)
chmod 400  # r-------- Read-only (very restrictive)

⚡ Process Management

# View running processes
ps aux                         # All processes, detailed
ps aux | grep nginx            # Filter for specific process
ps -ef                         # Full format listing

# Interactive process viewer
top                            # Press q to quit
htop                           # Enhanced (install if needed)

# Process signals
kill PID                       # Send SIGTERM (graceful stop)
kill -9 PID                    # Send SIGKILL (force kill)
killall nginx                  # Kill all processes named nginx
pkill -f "python app.py"       # Kill by pattern match

# Background jobs
command &                      # Run in background
jobs                           # List background jobs
fg                             # Bring last job to foreground
fg %1                          # Bring job 1 to foreground
bg %1                          # Resume job 1 in background
Ctrl+Z                         # Suspend current process
Ctrl+C                         # Terminate current process

# Process priority
nice -n 10 command             # Run with lower priority
renice -n 5 -p PID             # Change priority of running process

# System resource info
free -h                        # Memory usage (human readable)
df -h                          # Disk space usage
df -h /                        # Specific filesystem
du -sh directory/              # Directory size
du -sh *                       # Size of each item in current dir
uptime                         # System uptime and load average
lscpu                          # CPU information
uname -a                       # Kernel and system info

🌐 Networking

# Network interfaces
ip a                           # Show all interfaces and IPs
ip addr show eth0              # Specific interface
ifconfig                       # Older alternative

# Connectivity testing
ping google.com
ping -c 4 google.com          # Only 4 packets
ping -i 0.5 google.com        # Ping every 0.5 seconds

# DNS lookup
nslookup google.com
dig google.com
dig google.com A               # A record only
dig +short google.com          # IP only
host google.com

# Trace network path
traceroute google.com
tracepath google.com

# Active connections
netstat -tuln                  # Listening ports (TCP+UDP)
netstat -tulnp                 # With process names (requires sudo)
ss -tuln                       # Modern alternative to netstat
ss -tulnp                      # With process names

# Port checking
nc -zv hostname 80             # Check if port is open
nc -zv hostname 80-100         # Check port range

# Download files
curl -O https://example.com/file.zip       # Download file
curl -L -o output.zip https://example.com/ # Follow redirects, save as
wget https://example.com/file.zip          # Alternative to curl
curl -I https://example.com               # Headers only
curl -X POST -d '{"key":"val"}' -H "Content-Type: application/json" https://api.com

# SSH
ssh user@hostname
ssh -p 2222 user@hostname      # Custom port
ssh -i ~/.ssh/key.pem user@hostname  # Specific key
ssh -L 8080:localhost:80 user@hostname  # Port forwarding (local)
ssh -R 8080:localhost:80 user@hostname  # Port forwarding (remote)

# SCP — secure copy
scp file.txt user@host:/path/
scp -r directory/ user@host:/path/
scp user@host:/path/file.txt ./local/

# Firewall (ufw — Ubuntu)
sudo ufw status
sudo ufw enable
sudo ufw allow 22/tcp
sudo ufw allow 80
sudo ufw deny 3306
sudo ufw delete allow 80

🔎 Text Processing

# Search in files
grep "search term" file.txt
grep -i "search"  file.txt    # Case insensitive
grep -r "search" directory/   # Recursive
grep -n "search" file.txt     # Show line numbers
grep -v "exclude" file.txt    # Invert match (exclude)
grep -c "search" file.txt     # Count matches
grep -l "search" *.txt        # List matching filenames only
grep -A 3 "search" file.txt   # 3 lines after match
grep -B 3 "search" file.txt   # 3 lines before match
grep -E "regex|pattern" file  # Extended regex

# Stream editor — find and replace
sed 's/old/new/' file.txt                # Replace first occurrence per line
sed 's/old/new/g' file.txt              # Replace all occurrences
sed 's/old/new/gi' file.txt            # Case insensitive
sed -i 's/old/new/g' file.txt          # Edit file in place
sed -n '5,10p' file.txt                # Print lines 5-10
sed '/pattern/d' file.txt              # Delete matching lines

# awk — column/field processing
awk '{print $1}' file.txt             # Print first column
awk '{print $1, $3}' file.txt         # Print columns 1 and 3
awk -F',' '{print $2}' data.csv       # Use comma delimiter
awk 'NR==5' file.txt                  # Print line 5
awk '/pattern/ {print $0}' file.txt   # Print matching lines
awk '{sum += $1} END {print sum}' f   # Sum first column

# Sort
sort file.txt                          # Alphabetical
sort -r file.txt                       # Reverse
sort -n file.txt                       # Numerical
sort -k2 file.txt                      # Sort by column 2
sort -u file.txt                       # Sort and remove duplicates

# Other text tools
cut -d',' -f1,3 data.csv              # Extract columns 1 and 3
uniq file.txt                          # Remove consecutive duplicates
uniq -c file.txt                       # Count occurrences
tr 'a-z' 'A-Z' < file.txt            # Translate characters
tr -d '\r' < file.txt                 # Delete carriage returns
diff file1.txt file2.txt              # Compare files
wc -l file.txt                        # Line count

📦 Package Management

# --- Ubuntu / Debian (apt) ---
sudo apt update                        # Update package list
sudo apt upgrade                       # Upgrade installed packages
sudo apt install package-name
sudo apt remove package-name
sudo apt purge package-name           # Remove with config files
sudo apt autoremove                   # Remove unused dependencies
apt search package-name
apt show package-name

# --- CentOS / RHEL (yum/dnf) ---
sudo dnf update
sudo dnf install package-name
sudo dnf remove package-name
dnf search package-name

# --- macOS (Homebrew) ---
brew update
brew install package-name
brew uninstall package-name
brew upgrade
brew list
brew search package-name
brew info package-name

🔧 Bash Scripting Essentials

#!/usr/bin/env bash
# Shebang line — always first line of scripts

# Variables
NAME="Alice"
AGE=30
echo "Name: $NAME"
echo "Name: ${NAME}"          # Braces — needed for concatenation

# Reading input
read -p "Enter your name: " USER_NAME

# Conditionals
if [ "$NAME" = "Alice" ]; then
    echo "Hello Alice"
elif [ "$AGE" -gt 18 ]; then
    echo "You are an adult"
else
    echo "Unknown"
fi

# String tests
[ -z "$VAR" ]     # True if empty
[ -n "$VAR" ]     # True if not empty
[ "$A" = "$B" ]   # True if equal
[ "$A" != "$B" ]  # True if not equal

# Numeric tests
[ $A -eq $B ]     # Equal
[ $A -ne $B ]     # Not equal
[ $A -gt $B ]     # Greater than
[ $A -lt $B ]     # Less than
[ $A -ge $B ]     # Greater or equal
[ $A -le $B ]     # Less or equal

# File tests
[ -f "file.txt" ]   # True if regular file exists
[ -d "dir/" ]       # True if directory exists
[ -e "path" ]       # True if path exists
[ -r "file" ]       # True if readable
[ -x "file" ]       # True if executable
[ -s "file" ]       # True if non-empty

# Loops
for i in 1 2 3 4 5; do
    echo "Item: $i"
done

for file in *.txt; do
    echo "Processing: $file"
done

for ((i=0; i<10; i++)); do
    echo $i
done

while [ $count -lt 5 ]; do
    count=$((count + 1))
done

# Functions
greet() {
    local name="$1"         # $1 = first argument
    echo "Hello, $name!"
}
greet "Alice"

# Exit codes
command && echo "Success"   # Run if previous succeeded
command || echo "Failed"    # Run if previous failed
exit 0                      # Successful exit
exit 1                      # Error exit

# Useful patterns
set -e                      # Exit on any error
set -u                      # Error on undefined variables
set -o pipefail             # Fail on pipe errors
set -x                      # Debug mode (print commands)

⚙️ System Administration

# User management
whoami                              # Current user
id                                  # User ID and groups
sudo command                        # Run as root
sudo -u alice command               # Run as specific user
su - alice                          # Switch to user alice

# Adding/modifying users
sudo adduser alice
sudo passwd alice                   # Change password
sudo usermod -aG sudo alice         # Add to sudo group
sudo deluser alice

# Service management (systemd)
sudo systemctl start nginx
sudo systemctl stop nginx
sudo systemctl restart nginx
sudo systemctl reload nginx
sudo systemctl status nginx
sudo systemctl enable nginx         # Start on boot
sudo systemctl disable nginx
sudo systemctl list-units --type=service  # List services

# Logs with journalctl
journalctl -u nginx                 # Logs for nginx service
journalctl -u nginx -f              # Follow logs
journalctl -u nginx --since "1 hour ago"
journalctl -p err                   # Error level only

# Cron jobs
crontab -e                          # Edit user cron
crontab -l                          # List user cron jobs
sudo crontab -e                     # Edit root cron

# Cron syntax: minute hour day month weekday command
# * * * * * /path/to/script.sh
# 0 2 * * * /backup.sh              # Daily at 2am
# */15 * * * * /health-check.sh     # Every 15 minutes
# 0 9 * * 1-5 /report.sh            # Weekdays at 9am

→ Related: Cybersecurity Fundamentals Guide | Python for Security Automation Tutorial | IT Fundamentals Learning Path

📬 New Cheatsheets Added Regularly

New quick-reference guides are added as the hub grows. Subscribe to the newsletter to know when new ones drop.

→ Subscribe to the Newsletter