# 🖥️ THE COMPLETE CLI MASTER GUIDE
### From Absolute Beginner to Advanced Professional
**By: Senior System Administrator & DevOps Engineer**

---

> **How to use this guide:** Read it top-to-bottom for a structured learning path, or jump to any section using the Table of Contents. Every concept builds on the previous one. Practice each command as you read — muscle memory is everything in CLI.

---

## 📚 TABLE OF CONTENTS

1. [Section 1 — Foundations: CLI, Kernel, Terminals & Shells](#section-1--foundations)
2. [Section 2 — File System Mastery](#section-2--file-system-mastery)
3. [Section 3 — Permissions & Security](#section-3--permissions--security)
4. [Section 4 — I/O Streams & Manipulation](#section-4--io-streams--manipulation)
5. [Section 5 — Text Processing Tools](#section-5--text-processing-tools)
6. [Section 6 — Process Management](#section-6--process-management)
7. [Section 7 — Networking & Connectivity](#section-7--networking--connectivity)
8. [Section 8 — Automation & Shell Scripting](#section-8--automation--shell-scripting)
9. [Section 9 — Advanced Workflow & Environment Customization](#section-9--advanced-workflow)

---

---

# SECTION 1 — FOUNDATIONS

## What is the CLI?

The **Command Line Interface (CLI)** is a text-based interface to interact with your operating system. Instead of clicking icons, you type commands. This gives you:

- **Speed** — A single command can do what 15 mouse-clicks would
- **Power** — Access system features that no GUI exposes
- **Automation** — Script repetitive tasks to run unattended
- **Remote Control** — Manage servers thousands of miles away
- **Reproducibility** — Commands are auditable, scriptable, and shareable

## How CLI Interacts with the OS — The Architecture

```
┌─────────────────────────────────────────────────┐
│                   YOU (User)                    │
│           Type commands, read output            │
└──────────────────────┬──────────────────────────┘
                       │
┌──────────────────────▼──────────────────────────┐
│              TERMINAL EMULATOR                  │
│   (Alacritty, iTerm2, GNOME Terminal, etc.)     │
│   Draws text on screen, captures keystrokes     │
└──────────────────────┬──────────────────────────┘
                       │
┌──────────────────────▼──────────────────────────┐
│                   SHELL                         │
│         (Bash, Zsh, Fish, PowerShell)           │
│   Interprets your commands, manages processes,  │
│   handles variables, scripts, and history       │
└──────────────────────┬──────────────────────────┘
                       │
┌──────────────────────▼──────────────────────────┐
│            SYSTEM CALL INTERFACE                │
│   Shell translates commands into system calls   │
└──────────────────────┬──────────────────────────┘
                       │
┌──────────────────────▼──────────────────────────┐
│                  KERNEL                         │
│   Core of the OS — manages CPU, memory, I/O,   │
│   processes, file systems, devices              │
└──────────────────────┬──────────────────────────┘
                       │
┌──────────────────────▼──────────────────────────┐
│                  HARDWARE                       │
│         CPU, RAM, Disk, Network Card            │
└─────────────────────────────────────────────────┘
```

### What is a Terminal?

A **terminal** (or terminal emulator) is just the window that displays text. It is the *glass* you look through. Popular terminals:

| Terminal       | Platform        | Notes                            |
|----------------|-----------------|----------------------------------|
| GNOME Terminal | Linux           | Default on Ubuntu                |
| Alacritty      | Cross-platform  | GPU-accelerated, very fast       |
| iTerm2         | macOS           | Feature-rich, split panes        |
| Windows Terminal | Windows       | Modern, supports multiple shells |

### What is a Shell?

A **shell** is the program running *inside* the terminal. It reads your text, interprets it, and executes programs. The shell is the *brain*.

| Shell       | Config File         | Best For                         |
|-------------|---------------------|----------------------------------|
| **Bash**    | `~/.bashrc`         | Universal, servers, scripting    |
| **Zsh**     | `~/.zshrc`          | Daily use, plugins, macOS default|
| **Fish**    | `~/.config/fish/`   | Beginners, autocomplete          |
| **PowerShell** | `$PROFILE`       | Windows, Azure, .NET automation  |
| **sh**      | none                | POSIX-compliant, embedded systems|

```bash
# See which shell you are currently using
echo $SHELL

# See all shells installed on your system
cat /etc/shells

# Switch to Zsh (if installed)
chsh -s /usr/bin/zsh

# Check your current Bash version
bash --version
```

### The Anatomy of a Command

```
┌─────────┬──────────────┬─────────────────────────────┐
│ COMMAND │    FLAGS     │          ARGUMENTS          │
├─────────┼──────────────┼─────────────────────────────┤
│   ls    │  -l  -a  -h  │       /home/username        │
└─────────┴──────────────┴─────────────────────────────┘

$ ls -lah /home/username
  │   │││  └── Argument: path to act upon
  │   ││└───── h: human-readable sizes
  │   │└────── a: show hidden files (dotfiles)
  │   └─────── l: long listing format
  └─────────── The command itself
```

### Pro Tips — Foundations

```bash
# The most important command — learn anything
man ls          # Read the manual for 'ls'
man bash        # The full Bash manual
tldr ls         # Simplified, community examples (install: npm install -g tldr)

# Get help inline (faster than man)
ls --help
grep --help

# Know where a command lives
which python3   # Shows: /usr/bin/python3
type ls         # Shows if it's a builtin, alias, or file
whereis grep    # Finds binary, source, and man page

# Run the previous command as root
sudo !!

# Tab completion — press TAB to auto-complete commands, paths, filenames
# Double-TAB shows all possible completions
```

---

---

# SECTION 2 — FILE SYSTEM MASTERY

## The Linux File System Hierarchy

```
/                           Root — everything starts here
├── bin/                    Essential user binaries (ls, cp, mv)
├── boot/                   Bootloader, kernel images
├── dev/                    Device files (disks, terminals)
├── etc/                    System-wide configuration files
├── home/                   User home directories
│   ├── alice/
│   └── bob/
├── lib/                    Shared libraries
├── media/                  Removable media mount points
├── mnt/                    Temporary mount points
├── opt/                    Optional/third-party software
├── proc/                   Virtual filesystem — running processes
├── root/                   Root user's home directory
├── sbin/                   System binaries (for root)
├── srv/                    Service data (web, ftp)
├── sys/                    Kernel & hardware info (virtual)
├── tmp/                    Temporary files (cleared on reboot)
├── usr/                    User programs and data
│   ├── bin/                Non-essential user binaries
│   ├── local/              Locally installed programs
│   └── share/              Architecture-independent data
└── var/                    Variable data — logs, databases, caches
    ├── log/
    └── www/
```

## Navigation

```bash
# Where am I?
pwd                         # Print Working Directory: /home/alice

# Move around
cd /etc                     # Absolute path (starts from root /)
cd Documents                # Relative path (from current location)
cd ..                       # Go up one level
cd ../..                    # Go up two levels
cd ~                        # Go to your home directory
cd -                        # Go back to PREVIOUS directory (very useful!)

# List files
ls                          # Basic listing
ls -l                       # Long format: permissions, owner, size, date
ls -a                       # All files including hidden (dotfiles)
ls -lah                     # Long + all + human-readable sizes
ls -lt                      # Sort by modification time (newest first)
ls -lS                      # Sort by size (largest first)
ls -R                       # Recursive — list all subdirectories
ls --color=auto             # Colorize output
```

## File Creation, Copying, Moving, Deleting

```bash
# Create
touch newfile.txt           # Create empty file (or update timestamp)
touch file1 file2 file3     # Create multiple files at once
mkdir mydir                 # Make directory
mkdir -p a/b/c              # Make nested directories (parents too)
mkdir -p project/{src,tests,docs}  # Brace expansion — create multiple dirs

# Copy
cp file.txt copy.txt        # Copy file
cp -r dir/ backup/          # Copy directory recursively
cp -p file.txt copy.txt     # Preserve permissions and timestamps
cp -i file.txt copy.txt     # Interactive — ask before overwriting

# Move and Rename (same command)
mv file.txt newname.txt     # Rename file
mv file.txt /tmp/           # Move file to /tmp/
mv -i src dest              # Interactive — ask before overwriting
mv -n src dest              # Never overwrite existing file

# Delete (BE CAREFUL — no trash bin in CLI)
rm file.txt                 # Remove file
rm -i file.txt              # Interactive — confirm each deletion
rm -r mydir/                # Remove directory and its contents recursively
rm -rf mydir/               # Force remove — no prompts (DANGEROUS)
rmdir emptydir/             # Remove EMPTY directory only

# Links
ln -s /path/to/target link_name    # Create symbolic (soft) link
ln /path/to/file hardlink_name     # Create hard link
```

## Advanced Finding — `find`

`find` is one of the most powerful CLI tools. It searches the filesystem in real-time.

```bash
# Syntax: find [where] [what] [action]

# Find by name
find /home -name "*.log"            # Find all .log files under /home
find . -name "config.yml"           # Find in current dir and below
find / -name "passwd" 2>/dev/null   # Find everywhere, suppress permission errors
find . -iname "readme*"             # Case-insensitive search

# Find by type
find . -type f                      # Files only
find . -type d                      # Directories only
find . -type l                      # Symbolic links only

# Find by size
find / -size +100M                  # Files larger than 100 MB
find . -size -1k                    # Files smaller than 1 KB
find . -size +1M -size -500M        # Between 1MB and 500MB

# Find by time (days)
find . -mtime -7                    # Modified within last 7 days
find . -mtime +30                   # Modified more than 30 days ago
find . -atime -1                    # Accessed in last 24 hours
find . -newer reference.txt         # Newer than reference.txt

# Find by permissions
find /var/www -perm 777             # Exact permissions 777
find . -perm /u+x                   # User-executable files

# Find by owner
find /home -user alice              # Files owned by alice
find / -group developers 2>/dev/null

# Execute actions on found files
find . -name "*.tmp" -delete        # Find and delete .tmp files
find . -name "*.sh" -exec chmod +x {} \;   # Make all .sh files executable
find . -type f -exec ls -lh {} \;          # List details of each found file
find . -name "*.log" -exec rm -f {} +      # Delete (faster + batching)

# Combine conditions
find . -type f -name "*.py" -size +10k     # Python files over 10KB
find . -not -name "*.git"                  # Exclude .git files
find . -name "*.log" -or -name "*.tmp"     # OR condition
```

## Fast Searching — `locate`

`locate` uses a pre-built database — much faster than `find` but not real-time.

```bash
locate passwd               # Find all files named 'passwd'
locate -i readme            # Case-insensitive
locate "*.conf" | head -20  # Find .conf files, show first 20

# Update the database (run as root, or it may be outdated)
sudo updatedb

# When to use which:
# locate = fast, for finding installed files you know exist
# find   = real-time, for complex queries on live filesystem
```

## Disk Usage — `du` and `df`

```bash
# df — Disk Free — shows FILESYSTEM usage
df -h                       # Human-readable sizes
df -hT                      # Include filesystem type
df -h /home                 # Show usage for specific mount point

# Sample output:
# Filesystem      Size  Used Avail Use% Mounted on
# /dev/sda1        50G   23G   25G  48% /
# tmpfs           7.8G  1.2M  7.8G   1% /run

# du — Disk Usage — shows DIRECTORY usage
du -h file.txt              # Size of a specific file
du -sh /var/log             # Summary of /var/log directory (-s = summarize)
du -sh /*                   # Size of every top-level directory
du -h --max-depth=1 /home   # One level deep in /home
du -sh * | sort -rh         # Sort directories by size (largest first)

# Find the top 10 largest directories
du -sh /* 2>/dev/null | sort -rh | head -10

# Find the top 10 largest files
find / -type f -printf '%s %p\n' 2>/dev/null | sort -rn | head -10 | awk '{print $1/1024/1024 "MB " $2}'
```

## Pro Tips — File System

```bash
# Quickly view file contents
cat file.txt                # Print entire file
less file.txt               # Page through file (q to quit, / to search)
more file.txt               # Older pager
head -n 20 file.txt         # First 20 lines
tail -n 20 file.txt         # Last 20 lines
tail -f /var/log/syslog     # LIVE follow — watch file as it grows (great for logs!)
tail -F /var/log/app.log    # Follow even if file is rotated

# Word count and file stats
wc file.txt                 # Lines, words, characters
wc -l file.txt              # Count lines only
wc -w file.txt              # Count words only

# View file type (not just extension)
file image.png              # Outputs: PNG image data, 1920 x 1080...
file mystery_file           # Detects binary, text, scripts, etc.

# Compare files
diff file1.txt file2.txt    # Show differences
diff -u file1.txt file2.txt # Unified format (used in patches)
vimdiff file1.txt file2.txt # Side-by-side in vim

# Sort and unique
sort names.txt              # Sort alphabetically
sort -n numbers.txt         # Numeric sort
sort -rn numbers.txt        # Reverse numeric sort
sort -u names.txt           # Sort and remove duplicates
uniq sorted.txt             # Remove consecutive duplicates
sort names.txt | uniq -c    # Count occurrences

# BRACE EXPANSION — very powerful
echo {a,b,c}.txt            # a.txt b.txt c.txt
mkdir -p project/{src,lib,tests,docs}/{v1,v2}
cp config.yml config.yml.{bak,$(date +%Y%m%d)}  # Create dated backup
```

---

---

# SECTION 3 — PERMISSIONS & SECURITY

## Understanding the Permission Model

Every file and directory in Linux has three sets of permissions for three categories of users.

```
┌──────────────────────────────────────────────────────────────────┐
│  FILE:  /home/alice/report.txt                                   │
│                                                                  │
│  $ ls -l report.txt                                              │
│  -rwxr-xr--  1  alice  developers  4096  Apr 30 10:00 report.txt│
│  │├──┤├──┤├─┤     │        │                                     │
│  ││  │ │  │ │     │        └── Group owner                       │
│  ││  │ │  │ │     └────────── User owner                         │
│  ││  │ │  │ └──────────────── Others permissions (r--)           │
│  ││  │ └──┴────────────────── Group permissions (r-x)            │
│  │└──┴──────────────────────── User permissions (rwx)            │
│  └──────────────────────────── File type (- = file, d = dir)     │
└──────────────────────────────────────────────────────────────────┘

File Types:
  -   Regular file
  d   Directory
  l   Symbolic link
  c   Character device
  b   Block device
  p   Named pipe (FIFO)
  s   Socket

Permissions:
  r   Read    (4) — view file contents / list directory
  w   Write   (2) — modify file / create files in directory
  x   Execute (1) — run file as program / enter directory
  -   No permission
```

## The Octal (Numeric) Permission System

Each permission is a bit. Three permissions per group = 3 bits = octal digit (0–7).

```
┌─────────────────────────────────────────────────┐
│          OCTAL PERMISSION TABLE                 │
├───────┬───┬───┬───┬───────────────────────────  │
│ Octal │ r │ w │ x │ Meaning                     │
├───────┼───┼───┼───┼─────────────────────────── │
│   0   │ - │ - │ - │ No permissions              │
│   1   │ - │ - │ x │ Execute only                │
│   2   │ - │ w │ - │ Write only                  │
│   3   │ - │ w │ x │ Write + Execute             │
│   4   │ r │ - │ - │ Read only                   │
│   5   │ r │ - │ x │ Read + Execute              │
│   6   │ r │ w │ - │ Read + Write                │
│   7   │ r │ w │ x │ Full permissions            │
└───────┴───┴───┴───┴─────────────────────────── ┘

THREE digits = User | Group | Others
chmod 754 file.txt
      │││
      ││└── Others: 4 = r--  (read only)
      │└─── Group:  5 = r-x  (read + execute)
      └──── User:   7 = rwx  (full)
```

## `chmod` — Change File Mode (Permissions)

```bash
# Numeric (octal) method
chmod 755 script.sh         # rwxr-xr-x — typical for scripts/dirs
chmod 644 file.txt          # rw-r--r-- — typical for files
chmod 600 private_key       # rw------- — SSH private key
chmod 777 file.txt          # rwxrwxrwx — full for all (AVOID in production)
chmod 000 file.txt          # ---------- no permissions

# Symbolic method (more readable)
chmod u+x script.sh         # Add execute for User
chmod g-w file.txt          # Remove write from Group
chmod o+r file.txt          # Add read for Others
chmod a+x script.sh         # Add execute for All (u+g+o)
chmod u=rwx,g=rx,o=r file   # Set exact permissions symbolically

# Recursive — apply to directories and all contents
chmod -R 755 /var/www/      # All files in /var/www
chmod -R u+rw,go-w mydir/   # Symbolic recursive

# Common Permission Patterns
# 755 (rwxr-xr-x) — Directories, public scripts
# 644 (rw-r--r--) — Regular files, config files
# 700 (rwx------) — Private scripts, home dir
# 600 (rw-------) — Private files, SSH keys
# 400 (r--------) — Read-only sensitive files
```

## `chown` — Change Ownership

```bash
# Syntax: chown [user]:[group] file

chown alice file.txt                # Change owner to alice
chown alice:developers file.txt     # Change owner AND group
chown :developers file.txt          # Change group only (same as chgrp)
chown -R alice:www-data /var/www/   # Recursive ownership change

# chgrp — change group specifically
chgrp developers project/
chgrp -R www-data /var/www/html/

# View current ownership
ls -l file.txt              # Shows owner and group
stat file.txt               # Full metadata including ownership, times

# See what groups you belong to
id                          # uid=1000(alice) gid=1000(alice) groups=...
groups                      # Just the group names
id username                 # Check another user's groups
```

## Special Permission Bits

```bash
# SetUID (SUID) — file runs as owner, not executor
chmod u+s /usr/bin/program  # Numeric: add 4000
chmod 4755 program          # rwsr-xr-x
# Example: /usr/bin/passwd runs as root even when called by normal user

# SetGID (SGID) — on dirs, new files inherit group
chmod g+s /shared/          # Numeric: add 2000
chmod 2755 /shared/         # rwxr-sr-x
# Files created in /shared/ inherit the directory's group

# Sticky Bit — on dirs, only owner can delete their own files
chmod +t /tmp/              # Numeric: add 1000
chmod 1777 /tmp/            # rwxrwxrwt
# Used on /tmp — you can't delete other users' temp files

# Full special bits: SUID=4, SGID=2, Sticky=1
chmod 4755 program          # SUID + 755
chmod 2755 shared_dir/      # SGID + 755
chmod 1777 /tmp/            # Sticky + 777
```

## `umask` — Default Permission Mask

```bash
umask                       # Show current mask (e.g., 022)
umask 027                   # Set mask (only for this session)

# How umask works:
# New FILE base:  666 (rw-rw-rw-)
# New DIR base:   777 (rwxrwxrwx)
# umask 022 means: 666 - 022 = 644 for files
#                  777 - 022 = 755 for dirs

# Set permanently by adding to ~/.bashrc:
# umask 027   ← files: 640, dirs: 750 (more restrictive)
```

## Pro Tips — Permissions

```bash
# Find files with dangerous permissions
find / -perm -4000 2>/dev/null          # SUID files
find / -perm -2000 2>/dev/null          # SGID files
find /var/www -perm 777 2>/dev/null     # World-writable files (security risk)

# Check if you can write to a file without ls -l
test -w file.txt && echo "Writable" || echo "Not writable"
test -r file.txt && echo "Readable"
test -x script.sh && echo "Executable"

# Access Control Lists (ACLs) — granular permissions
getfacl file.txt            # View ACLs
setfacl -m u:bob:rw file.txt        # Give bob read+write
setfacl -m g:contractors:r file.txt # Give group read-only
setfacl -x u:bob file.txt           # Remove bob's ACL entry
```

---

---

# SECTION 4 — I/O STREAMS & MANIPULATION

## The Three Standard Streams

Every Linux process has three data streams connected by default:

```
┌─────────────────────────────────────────────────────────┐
│                    A PROCESS                            │
│                                                         │
│  ┌──────────┐        ┌─────────────────────────────┐   │
│  │ stdin  0 │◄───────│  Keyboard / another program  │   │
│  │ stdout 1 │────────►  Terminal / file / pipe      │   │
│  │ stderr 2 │────────►  Terminal / file / /dev/null │   │
│  └──────────┘        └─────────────────────────────┘   │
│                                                         │
│  File Descriptor Numbers:                               │
│    0 = stdin  (standard input)                          │
│    1 = stdout (standard output) — normal results        │
│    2 = stderr (standard error)  — error messages        │
└─────────────────────────────────────────────────────────┘
```

## Redirection

```bash
# STDOUT Redirection
ls -l > filelist.txt            # Write stdout to file (OVERWRITE)
ls -l >> filelist.txt           # Append stdout to file
echo "Hello" > greeting.txt

# STDERR Redirection
find / -name foo 2> errors.txt          # Write errors to file
find / -name foo 2>> errors.txt         # Append errors to file
find / -name foo 2>/dev/null            # Discard all errors (/dev/null = black hole)

# Redirect BOTH stdout and stderr
command > output.txt 2>&1       # Both to same file (traditional)
command &> output.txt           # Modern Bash shorthand (same result)
command > output.txt 2> error.txt  # To different files

# STDIN Redirection
sort < unsorted.txt             # Feed file as input to sort
mysql -u root -p dbname < dump.sql  # Run SQL from file

# Here Document (heredoc) — multi-line stdin
cat << EOF > config.txt
server=localhost
port=3306
user=admin
EOF

# Here String — single line stdin
grep "pattern" <<< "some text to search"
base64 <<< "hello world"
```

## Piping — The Unix Philosophy

Pipes (`|`) connect the stdout of one command to the stdin of the next. This lets you build powerful processing pipelines.

```
Command 1    │     Command 2    │    Command 3
─────────────┼──────────────────┼──────────────────
ls -lah      │  grep ".log"     │  sort -k5 -rh
(list files) │ (filter .log)    │ (sort by size)
             │                  │
stdout ──────► stdin  stdout ───► stdin  stdout ──► Terminal
```

```bash
# Basic pipes
ls -la | grep ".txt"                    # List only .txt files
cat /etc/passwd | grep "alice"          # Find alice in passwd
ps aux | grep "nginx"                   # Find nginx processes
history | grep "git"                    # Find git commands you've run

# Multi-stage pipelines
cat /var/log/auth.log | grep "Failed" | awk '{print $11}' | sort | uniq -c | sort -rn | head -10
# Reads auth log ► finds failures ► extracts IP ► sorts ► counts ► top 10 attackers

# Count something
ls -la | wc -l                          # How many files in directory
cat file.txt | wc -w                    # Count words in file
ps aux | grep -v "grep" | wc -l        # Count running processes

# tee — write to file AND pass through pipe simultaneously
ls -la | tee filelist.txt | grep ".sh"
# filelist.txt gets full output; terminal shows only .sh files

# Process substitution (advanced)
diff <(ls dir1/) <(ls dir2/)            # Compare directory listings
```

## Advanced Redirection

```bash
# Order matters for redirection!
command > file 2>&1             # CORRECT: stdout to file, then stderr to stdout (file)
command 2>&1 > file             # WRONG: stderr to terminal, stdout to file

# Redirect to multiple outputs
command | tee file.txt          # Output to terminal AND file
command | tee -a file.txt       # Append to file AND show on terminal
command | tee file1 file2       # Write to multiple files AND terminal

# Suppress all output (silent execution)
command > /dev/null 2>&1        # Discard everything
command &>/dev/null             # Bash shorthand

# Named pipes (FIFOs) — for inter-process communication
mkfifo mypipe
command1 > mypipe &             # Write to pipe in background
command2 < mypipe               # Read from pipe

# File descriptor manipulation
exec 3> logfile.txt             # Open FD 3 for writing
echo "Log entry" >&3            # Write to FD 3
exec 3>&-                       # Close FD 3
```

## Pro Tips — I/O

```bash
# Use process substitution for diff of command outputs
diff <(cat file1.txt) <(cat file2.txt)

# Run command on each line of a file
while read line; do echo "Processing: $line"; done < input.txt

# Send output of command as argument (command substitution)
echo "Today is $(date +%Y-%m-%d)"
echo "Files: $(ls | wc -l)"

# Null-delimited output for safe filename handling (handles spaces)
find . -name "*.txt" -print0 | xargs -0 rm

# Check if command succeeded (exit code)
ls /nonexistent
echo "Exit code: $?"   # 0 = success, non-zero = failure
```

---

---

# SECTION 5 — TEXT PROCESSING TOOLS

## `grep` — Global Regular Expression Print

`grep` searches for patterns in text. It's your most-used text tool.

```bash
# Basic usage
grep "error" logfile.txt            # Find lines containing "error"
grep "Error" logfile.txt            # Case-sensitive (default)
grep -i "error" logfile.txt         # Case-insensitive
grep -n "error" logfile.txt         # Show line numbers
grep -c "error" logfile.txt         # Count matching lines
grep -v "error" logfile.txt         # Invert match (lines WITHOUT "error")
grep -w "error" logfile.txt         # Match whole word only
grep -l "error" *.txt               # Only print filenames that match
grep -L "error" *.txt               # Files that do NOT match

# Context lines
grep -A 3 "error" log.txt           # 3 lines After match
grep -B 3 "error" log.txt           # 3 lines Before match
grep -C 3 "error" log.txt           # 3 lines before and after (Context)

# Recursive search
grep -r "TODO" ./src/               # Search all files in directory tree
grep -rn "function_name" ./         # With line numbers
grep -rl "password" /etc/           # Only print filenames

# Regular Expressions with grep
grep "^error" log.txt               # Lines STARTING with "error"
grep "error$" log.txt               # Lines ENDING with "error"
grep "err.r" log.txt                # . matches any single character
grep "err[oa]r" log.txt             # Match "error" or "errar"
grep "err[^o]r" log.txt             # NOT followed by 'o'
grep -E "error|warning|critical" log.txt   # Extended regex: OR
grep -E "err(or|and)" log.txt       # Grouping in extended regex
grep -E "[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}" log.txt  # IP addresses
grep -P "\d{4}-\d{2}-\d{2}" log.txt # Perl regex: match dates YYYY-MM-DD

# Useful real-world examples
grep -i "failed password" /var/log/auth.log | awk '{print $11}' | sort | uniq -c | sort -rn
# ↑ Find brute force attackers — top IPs with failed logins

grep -E "^(Jan|Feb|Mar)" log.txt    # Lines starting with month names
grep -v "^#" /etc/ssh/sshd_config   # Show config without comments
grep -v "^$" file.txt               # Remove blank lines
```

## `sed` — Stream Editor

`sed` edits text stream line-by-line without opening the file. Best for substitution and transformation.

```bash
# Basic substitution: s/pattern/replacement/flags
sed 's/hello/world/' file.txt           # Replace FIRST occurrence per line
sed 's/hello/world/g' file.txt          # Replace ALL occurrences (global)
sed 's/hello/world/gi' file.txt         # Case-insensitive + global
sed 's/hello/world/2' file.txt          # Replace 2nd occurrence per line

# In-place editing (modify file directly)
sed -i 's/hello/world/g' file.txt       # Edit in place
sed -i.bak 's/hello/world/g' file.txt   # Edit in place, keep backup as .bak

# Delete lines
sed '/pattern/d' file.txt              # Delete lines matching pattern
sed '/^#/d' config.txt                 # Delete comment lines
sed '/^$/d' file.txt                   # Delete blank lines
sed '5d' file.txt                      # Delete line 5
sed '2,8d' file.txt                    # Delete lines 2 through 8

# Print specific lines
sed -n '5p' file.txt                   # Print only line 5 (-n suppresses default output)
sed -n '2,8p' file.txt                 # Print lines 2–8
sed -n '/error/p' file.txt             # Print lines matching pattern

# Insert and append
sed '3i\New line before line 3' file.txt    # Insert before line 3
sed '3a\New line after line 3' file.txt     # Append after line 3
sed '/pattern/a\Added after match' file.txt # Append after matching line

# Multiple operations
sed -e 's/foo/bar/g' -e 's/baz/qux/g' file.txt   # Chain operations
sed -e '/^#/d' -e '/^$/d' config.txt               # Remove comments AND blank lines

# Address ranges
sed '1,5s/foo/bar/g' file.txt          # Substitute only in lines 1–5
sed '/start/,/end/d' file.txt          # Delete from "start" to "end"

# Real-world examples
# Update version in config file
sed -i 's/version=.*/version=2.0.0/' app.conf

# Remove Windows CRLF line endings
sed -i 's/\r//' file.txt

# Add line numbers to file
sed = file.txt | sed 'N;s/\n/\t/'

# Comment out a specific line
sed -i '/^ServerName/s/^/#/' httpd.conf
```

## `awk` — Pattern Scanning and Processing

`awk` is a full programming language for text processing. It reads line by line, splits fields, and processes data.

```bash
# awk's model:
# For each line → split into fields $1, $2, $3... ($0 = whole line)
# FS = Field Separator (default: whitespace)
# NR = current line Number, NF = Number of Fields

# Basic syntax
awk '{print $1}' file.txt              # Print first field of each line
awk '{print $1, $3}' file.txt          # Print fields 1 and 3
awk '{print NR, $0}' file.txt          # Print line number + full line
awk '{print NF, $0}' file.txt          # Print field count + line
awk 'END {print NR}' file.txt          # Count total lines (like wc -l)

# Field separators
awk -F: '{print $1}' /etc/passwd       # Split on colon, print usernames
awk -F, '{print $2}' data.csv          # CSV — print second column
awk -F'\t' '{print $3}' data.tsv       # Tab-separated, third column
awk 'BEGIN{FS=":"} {print $1}' /etc/passwd   # Set FS in BEGIN block

# Conditions and filtering
awk '$3 > 1000' /etc/passwd            # Lines where field 3 > 1000
awk '/error/ {print}' log.txt          # Print lines matching pattern (like grep)
awk '!/^#/ {print}' config.txt         # Lines NOT starting with #
awk 'NR==5' file.txt                   # Print only line 5
awk 'NR>=2 && NR<=8' file.txt          # Print lines 2–8

# Arithmetic and calculations
awk '{sum += $1} END {print "Sum:", sum}' numbers.txt
awk '{sum += $1; count++} END {print "Average:", sum/count}' numbers.txt
awk 'NR>1 {sum += $5} END {print sum}' data.csv   # Sum column 5, skip header

# String formatting
awk '{printf "%-20s %5d\n", $1, $2}' data.txt      # Formatted output
awk '{printf "Name: %s, Age: %d\n", $1, $2}' data.txt

# BEGIN and END blocks
awk 'BEGIN {print "=== REPORT ==="} 
     {print $1, $2} 
     END {print "=== DONE ==="}' file.txt

# Multiple conditions
awk '{if ($3 > 50) print $1, "PASS"; else print $1, "FAIL"}' scores.txt

# Arrays (powerful for aggregation)
awk '{count[$1]++} END {for (k in count) print k, count[k]}' log.txt
# ↑ Count occurrences of each unique value in column 1

# Practical real-world examples

# Show only username and shell from /etc/passwd
awk -F: '{print $1, $7}' /etc/passwd

# Calculate total disk usage from du output
du -sh /home/*/ | awk '{sum += $1} END {print "Total:", sum "G"}'

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

# Find processes using more than 50% CPU
ps aux | awk '$3 > 50.0 {print $0}'

# Extract only failed SSH attempts with IPs
grep "Failed password" /var/log/auth.log | awk '{print $11}' | sort | uniq -c | sort -rn

# Sum the 5th column of a CSV, skipping the header
awk -F, 'NR>1 {sum += $5} END {print "Total:", sum}' sales.csv
```

## Pro Tips — Text Processing

```bash
# Combine tools in pipelines
cat /etc/passwd | grep -v "nologin" | awk -F: '{print $1}' | sort
# Show users who CAN log in

# Use cut for simple field extraction (faster than awk for simple jobs)
cut -d: -f1 /etc/passwd             # Cut on colon, show field 1
cut -d, -f1,3 data.csv              # CSV: show columns 1 and 3
cut -c1-10 file.txt                 # First 10 characters per line

# tr — translate characters
echo "hello world" | tr 'a-z' 'A-Z'   # Uppercase
echo "hello world" | tr -d ' '         # Delete spaces
echo "line1\nline2" | tr '\n' ','       # Replace newlines with commas
cat file.txt | tr -s ' '               # Squeeze multiple spaces into one

# Multi-tool pipeline example: Analyze web server logs
cat access.log | \
  awk '{print $7}' | \               # Extract URL field
  grep -v "\.css\|\.js\|\.png" | \   # Remove static assets
  sort | uniq -c | sort -rn | \      # Count and sort
  head -20                            # Top 20 most-requested URLs
```

---

---

# SECTION 6 — PROCESS MANAGEMENT

## What is a Process?

When you run a program, the OS creates a **process** — an instance of that program in execution. Each process has:
- A unique **PID** (Process ID)
- A **PPID** (Parent Process ID)
- Ownership (user who ran it)
- Resource usage (CPU, memory)
- A state (running, sleeping, zombie)

## Viewing Processes

```bash
# ps — process snapshot
ps                          # Your processes in this terminal
ps aux                      # ALL processes, ALL users (full info)
ps -ef                      # All processes in full-format (POSIX style)
ps aux --sort=-%cpu         # Sort by CPU usage (highest first)
ps aux --sort=-%mem         # Sort by memory usage
ps -u alice                 # Only alice's processes
ps --ppid 1234              # Children of process 1234

# ps output columns:
# USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
# VSZ = Virtual memory, RSS = Resident (physical) memory

# pgrep — find process by name
pgrep nginx                 # Get PIDs of nginx
pgrep -l nginx              # PID + name
pgrep -u alice              # All of alice's PIDs
pgrep -a "python"           # PID + full command line

# pstree — visualize process tree
pstree                      # Show process hierarchy
pstree -p                   # Include PIDs
pstree -u                   # Include usernames
```

## Interactive Monitoring

```bash
# top — classic interactive process monitor
top
# Inside top:
#   k = kill process (enter PID)
#   r = renice (change priority)
#   q = quit
#   P = sort by CPU (default)
#   M = sort by memory
#   1 = toggle per-CPU usage
#   f = field selection
#   u = filter by user

# htop — improved, modern top (install: sudo apt install htop)
htop
# Inside htop:
#   F2 = settings
#   F5 = tree view
#   F6 = sort by column
#   F9 = kill
#   F10 = quit
#   Space = tag process
#   / = search processes

# bottom (btm) — modern resource monitor (install separately)
# glances — comprehensive system monitor (pip install glances)
```

## Signals and Killing Processes

```bash
# kill — send a signal to a process
kill PID                    # Send SIGTERM (15) — polite request to stop
kill -9 PID                 # Send SIGKILL — forceful, cannot be ignored
kill -15 PID                # Explicitly SIGTERM
kill -1 PID                 # SIGHUP — reload config (for daemons)
kill -l                     # List all signals

# killall — kill by name
killall nginx               # Kill all nginx processes
killall -9 python           # Force kill all python processes
killall -u alice            # Kill all of alice's processes

# pkill — kill by pattern
pkill firefox               # Kill processes matching "firefox"
pkill -f "python script.py" # Match against full command line
pkill -9 -u alice           # Force kill all of alice's processes

# Common signals:
# SIGTERM (15) — graceful termination (default kill)
# SIGKILL  (9) — force kill, cannot be caught or ignored
# SIGHUP   (1) — hangup; reload config for daemons
# SIGINT   (2) — interrupt (same as Ctrl+C)
# SIGSTOP (19) — pause process (cannot be caught)
# SIGCONT (18) — continue paused process
```

## Background and Foreground Jobs

```bash
# Run in background
command &                   # Start command in background
sleep 100 &                 # Example — runs in background

# Job control
jobs                        # List background jobs
jobs -l                     # With PIDs
fg                          # Bring last background job to foreground
fg %1                       # Bring job 1 to foreground
bg %1                       # Send stopped job to background
Ctrl+Z                      # Suspend (pause) current foreground job
Ctrl+C                      # Interrupt (kill) current foreground job

# nohup — survive terminal logout
nohup command &             # Keeps running even after you close terminal
nohup python3 server.py &   # Output goes to nohup.out by default
nohup python3 server.py > app.log 2>&1 &  # Custom log file

# disown — detach a running job from terminal
jobs                        # Find job number
disown %1                   # Detach job 1 — won't be killed on logout
disown -a                   # Disown all jobs
```

## Process Priority — `nice` and `renice`

```bash
# Priority range: -20 (highest) to 19 (lowest)
# Default: 0. Normal users can only INCREASE niceness (lower priority)

nice -n 10 command          # Start command at niceness 10 (lower priority)
nice -n -5 command          # Start at -5 (higher priority, needs root)
sudo nice -n -20 command    # Highest priority

renice 10 -p 1234           # Change niceness of running PID 1234
renice 5 -u alice           # Change niceness of all of alice's processes
sudo renice -10 -p 1234     # Increase priority (root required)
```

## System Resource Monitoring

```bash
# Memory usage
free -h                     # RAM and swap usage (human-readable)
free -m                     # In megabytes
cat /proc/meminfo           # Detailed memory info from kernel

# CPU info
nproc                       # Number of CPU cores
lscpu                       # Detailed CPU architecture info
cat /proc/cpuinfo           # Raw CPU info

# System load and uptime
uptime                      # Uptime + load averages (1, 5, 15 min)
w                           # Who's logged in + load average
vmstat 1 5                  # Virtual memory stats every 1s for 5s
iostat -x 1                 # I/O statistics (install sysstat)
sar -u 1 10                 # CPU activity every 1s for 10 iterations

# Open files and network connections
lsof                        # List open files (everything is a file in Linux)
lsof -p 1234                # Files opened by PID 1234
lsof -u alice               # Files opened by alice
lsof -i :80                 # What's using port 80
lsof -i TCP                 # All TCP connections
```

## Pro Tips — Process Management

```bash
# Watch — repeat a command every N seconds
watch -n 2 'ps aux --sort=-%cpu | head -10'   # Update every 2s
watch -n 1 df -h                               # Monitor disk every second
watch -d 'ls -la'                              # Highlight changes (-d)

# Find and kill in one command
kill $(pgrep nginx)         # Kill by name using command substitution
pkill -9 -f "stuck_script.py"

# Run in background AND write to log
nohup ./deploy.sh > /var/log/deploy.log 2>&1 &
echo "Deployment PID: $!"   # $! = PID of last background process

# Limit CPU usage of a process
cpulimit -p 1234 -l 30      # Limit PID 1234 to 30% CPU (install cpulimit)

# Check if a service is running
systemctl status nginx       # systemd service status
systemctl start nginx        # Start service
systemctl stop nginx         # Stop service
systemctl restart nginx      # Restart
systemctl enable nginx       # Auto-start on boot
systemctl disable nginx      # Remove from autostart
journalctl -u nginx -f       # Follow nginx service logs
```

---

---

# SECTION 7 — NETWORKING & CONNECTIVITY

## Basic Network Information

```bash
# Network interfaces
ip addr                     # Show IP addresses (modern replacement for ifconfig)
ip addr show eth0           # Specific interface
ip link                     # Interface status (up/down)
ip route                    # Routing table
ip route show default       # Default gateway

ifconfig                    # Old tool (still works on most systems)
ifconfig -a                 # All interfaces including inactive

# DNS lookup
host google.com             # Simple DNS lookup
nslookup google.com         # Interactive DNS lookup
dig google.com              # Detailed DNS information
dig google.com MX           # Mail exchange records
dig +short google.com       # Just the IP address(es)
dig @8.8.8.8 google.com    # Query specific DNS server (8.8.8.8 = Google)

# Connectivity test
ping google.com             # Test connectivity (Ctrl+C to stop)
ping -c 5 google.com        # Send exactly 5 packets
ping -i 0.5 google.com      # Ping every 0.5 seconds
traceroute google.com       # Trace network path (install if missing)
mtr google.com              # Combined ping + traceroute (real-time)
```

## `curl` — Transfer Data with URLs

`curl` is the Swiss Army knife of web communication.

```bash
# Basic HTTP requests
curl https://example.com                    # GET request, show body
curl -I https://example.com                 # HEAD request — headers only
curl -i https://example.com                 # Include headers in output
curl -s https://example.com                 # Silent — no progress bar
curl -o output.html https://example.com     # Save to file
curl -O https://example.com/file.zip        # Save with original filename
curl -L https://example.com                 # Follow redirects (-L)
curl -v https://example.com                 # Verbose — show everything

# POST requests
curl -X POST https://api.example.com/data \
     -H "Content-Type: application/json" \
     -d '{"name": "alice", "role": "admin"}'

# With authentication
curl -u username:password https://api.example.com
curl -H "Authorization: Bearer TOKEN" https://api.example.com/protected

# Download with progress + resume capability
curl -C - -O https://example.com/largefile.iso     # Resume interrupted download

# API testing examples
# GET
curl -s https://api.github.com/users/torvalds | python3 -m json.tool

# POST with JSON
curl -X POST https://httpbin.org/post \
     -H "Content-Type: application/json" \
     -d '{"key": "value"}'

# Upload a file
curl -F "file=@/path/to/file.txt" https://upload.example.com

# Check HTTP response code
curl -o /dev/null -s -w "%{http_code}" https://example.com

# Useful curl flags:
# -s       Silent (no progress)
# -S       Show errors even with -s
# -L       Follow redirects
# -I       HEAD only
# -X       HTTP method
# -H       Add header
# -d       POST data
# -u       User:password
# -k       Skip SSL verification (insecure, for testing only)
# -m 10    Timeout after 10 seconds
# --retry 3  Retry 3 times on failure
```

## `wget` — Non-Interactive Downloader

```bash
# Basic download
wget https://example.com/file.zip               # Download to current dir
wget -O myfile.zip https://example.com/file.zip # Custom filename
wget -q https://example.com/file.zip            # Quiet — minimal output
wget -c https://example.com/largefile.iso       # Continue/resume download
wget -b https://example.com/file.zip            # Background download

# Mirror a website
wget --mirror -p --convert-links https://example.com

# Download multiple files from a list
wget -i urls.txt                    # File containing URLs, one per line

# Limit download speed
wget --limit-rate=1m https://example.com/file.zip  # 1 MB/s limit

# Recursive download
wget -r --level=2 https://example.com  # Download 2 levels deep
```

## `ssh` — Secure Shell

SSH lets you securely connect to remote machines.

```bash
# Basic connection
ssh user@hostname               # Connect as user to hostname
ssh user@192.168.1.100          # Using IP address
ssh -p 2222 user@hostname       # Non-standard port (default: 22)
ssh -i ~/.ssh/my_key user@host  # Use specific private key

# Run single command remotely (without interactive shell)
ssh user@host "ls -la /var/www"
ssh user@host "sudo systemctl restart nginx"
ssh user@host "df -h; free -h; uptime"  # Multiple commands

# SSH Key Setup (password-less authentication)
ssh-keygen -t ed25519 -C "your_email@example.com"  # Generate key pair
# Private key: ~/.ssh/id_ed25519
# Public key:  ~/.ssh/id_ed25519.pub

ssh-copy-id user@hostname       # Copy public key to remote host
# Or manually: cat ~/.ssh/id_ed25519.pub >> remote:~/.ssh/authorized_keys

# SSH config file (~/.ssh/config) — save connection profiles
# Example ~/.ssh/config:
# Host webserver
#     HostName 192.168.1.100
#     User alice
#     Port 22
#     IdentityFile ~/.ssh/my_key
#
# Then connect with just: ssh webserver

# SSH Tunneling
ssh -L 8080:localhost:80 user@remotehost       # Local forward: localhost:8080 → remote:80
ssh -R 9090:localhost:3000 user@remotehost     # Remote forward: remote:9090 → local:3000
ssh -D 1080 user@remotehost                    # Dynamic SOCKS proxy

# Keep connections alive
ssh -o ServerAliveInterval=60 user@host        # Send keepalive every 60s
# Or in ~/.ssh/config: ServerAliveInterval 60
```

## `scp` — Secure Copy (over SSH)

```bash
# Copy FROM remote TO local
scp user@host:/path/to/remote/file.txt /local/destination/
scp user@host:/var/log/app.log ./logs/

# Copy FROM local TO remote
scp /local/file.txt user@host:/remote/path/
scp deploy.sh user@192.168.1.100:/home/user/

# Copy directory recursively
scp -r /local/dir/ user@host:/remote/dir/
scp -r user@host:/remote/dir/ /local/backup/

# Specify port
scp -P 2222 file.txt user@host:/path/

# Tip: rsync is usually better than scp for large transfers
rsync -avz --progress /source/ user@host:/destination/
rsync -avz --delete /source/ user@host:/dest/  # Mirror (delete extra files)
```

## `netstat` / `ss` — Network Connections

```bash
# ss — modern replacement for netstat (preferred)
ss -tulpn                   # TCP+UDP, listening, process names, numeric
ss -an                      # All connections, numeric
ss -t                       # TCP connections only
ss -u                       # UDP connections only
ss -l                       # Listening ports only
ss -p                       # Show process names
ss -tnp | grep :80          # Who's using port 80

# netstat (older, may need net-tools package)
netstat -tulpn              # Same as ss: listen ports + processes
netstat -an                 # All connections
netstat -rn                 # Routing table

# Port scanning (check if ports are open)
nmap -p 80,443,22 hostname          # Check specific ports
nmap -sV hostname                   # Detect service versions
nmap -p- hostname                   # All 65535 ports (slow)

# Check what's on a specific port
ss -tlnp | grep :22         # Who owns port 22
fuser 80/tcp                # PID using port 80
lsof -i :443                # Process on port 443

# Test port connectivity
nc -zv hostname 80          # Test TCP port 80
nc -zv hostname 80-90       # Test port range
telnet hostname 80          # Old school port test
```

## Pro Tips — Networking

```bash
# Check your public IP
curl -s ifconfig.me
curl -s ipinfo.io/ip

# Monitor network traffic in real-time
iftop                       # Network bandwidth per connection (install first)
nethogs                     # Network usage per process (install first)
nload                       # Simple bandwidth monitor

# DNS debugging
dig +trace google.com       # Full DNS resolution trace
dig -x 8.8.8.8              # Reverse lookup (IP to hostname)

# HTTP debugging shortcut
curl -w "\n\nDNS: %{time_namelookup}s\nConnect: %{time_connect}s\nTotal: %{time_total}s\n" \
     -o /dev/null -s https://example.com

# Quick web server for testing (Python 3)
python3 -m http.server 8080     # Serve current directory on port 8080

# Check SSL certificate
echo | openssl s_client -connect google.com:443 2>/dev/null | openssl x509 -noout -dates
```

---

---

# SECTION 8 — AUTOMATION & SHELL SCRIPTING

## Why Shell Scripting?

Shell scripts automate repetitive tasks — system backups, deployment pipelines, log rotation, user provisioning. A good script runs at 3 AM while you're asleep.

## Script Structure and Basics

```bash
#!/usr/bin/env bash
# ↑ Shebang — tells OS which interpreter to use
# ALWAYS use this exact form (portable — works on any system)

# Script metadata header (professional practice)
# Script:      deploy.sh
# Description: Deploys the web application
# Author:      Alice <alice@example.com>
# Date:        2025-01-01
# Usage:       ./deploy.sh [environment] [version]

set -euo pipefail
# -e  Exit immediately on any error
# -u  Treat unset variables as errors
# -o pipefail  Pipeline fails if any command fails
# This trio makes scripts safe and predictable

# Make script executable and run it:
# chmod +x script.sh
# ./script.sh
```

## Variables

```bash
#!/usr/bin/env bash

# Variable assignment (NO spaces around =)
name="Alice"
age=30
pi=3.14159
greeting="Hello, $name!"   # Variable interpolation with double quotes
path_var='/usr/local/$name' # Single quotes — NO interpolation

echo $name                  # Access variable
echo "$name"                # BEST PRACTICE: always quote variables
echo "${name}"              # Explicit delimiters (needed: ${name}file)

# Command substitution — capture command output
today=$(date +%Y-%m-%d)
hostname=$(hostname)
user_count=$(cat /etc/passwd | wc -l)
echo "Today: $today, Host: $hostname, Users: $user_count"

# Arithmetic
count=5
count=$((count + 1))        # Integer arithmetic with $(( ))
result=$((10 * 5 + 3))
echo $((2 ** 10))           # 1024 (powers)

# Useful built-in variables
echo "$0"   # Script name
echo "$1"   # First argument
echo "$2"   # Second argument
echo "$@"   # All arguments as separate words
echo "$#"   # Number of arguments
echo "$?"   # Exit code of last command
echo "$$"   # Current script's PID
echo "$!"   # PID of last background process

# Variable defaults (safe variable expansion)
name="${1:-World}"               # If $1 is empty, use "World"
logdir="${LOG_DIR:-/var/log}"    # Use env var or default
echo "Hello, ${name}!"

# Read-only variables
readonly MAX_RETRIES=3
declare -r API_URL="https://api.example.com"
```

## User Input and Arguments

```bash
#!/usr/bin/env bash

# Read from user interactively
read -p "Enter your name: " username
read -sp "Enter password: " password   # -s = silent (no echo)
echo ""  # Newline after silent input
echo "Hello, $username"

# Script arguments
# Usage: ./script.sh Alice 30 admin
echo "Name: $1"
echo "Age: $2"
echo "Role: $3"
echo "All args: $@"
echo "Arg count: $#"

# Validate arguments
if [ "$#" -lt 2 ]; then
    echo "Usage: $0 <name> <environment>"
    exit 1
fi

# Parse named arguments with getopts
while getopts "u:p:vh" opt; do
    case $opt in
        u) username="$OPTARG" ;;
        p) password="$OPTARG" ;;
        v) verbose=true ;;
        h) echo "Usage: $0 -u user -p pass [-v]"; exit 0 ;;
        ?) echo "Invalid option: -$OPTARG"; exit 1 ;;
    esac
done
```

## Conditionals

```bash
#!/usr/bin/env bash

# if / elif / else
if [ condition ]; then
    # do something
elif [ other_condition ]; then
    # do something else
else
    # default
fi

# File tests
if [ -f /etc/passwd ]; then echo "File exists"; fi
if [ -d /home ]; then echo "Is a directory"; fi
if [ -x /usr/bin/python3 ]; then echo "Python is executable"; fi
if [ -w /tmp ]; then echo "Writable"; fi
if [ -s file.txt ]; then echo "File is non-empty"; fi
if [ ! -f /tmp/lock ]; then echo "Lock does not exist"; fi

# String comparisons (use double brackets [[ ]])
name="Alice"
if [[ "$name" == "Alice" ]]; then echo "It's Alice"; fi
if [[ "$name" != "Bob" ]]; then echo "Not Bob"; fi
if [[ -z "$name" ]]; then echo "Empty string"; fi     # -z = zero length
if [[ -n "$name" ]]; then echo "Non-empty string"; fi # -n = non-zero
if [[ "$name" =~ ^A ]]; then echo "Starts with A"; fi # Regex match

# Numeric comparisons
count=10
if [ "$count" -eq 10 ]; then echo "Equal to 10"; fi
if [ "$count" -ne 5 ]; then echo "Not equal to 5"; fi
if [ "$count" -gt 5 ]; then echo "Greater than 5"; fi
if [ "$count" -lt 20 ]; then echo "Less than 20"; fi
if [ "$count" -ge 10 ]; then echo "Greater or equal to 10"; fi
if [ "$count" -le 10 ]; then echo "Less or equal to 10"; fi

# Logical operators
if [[ "$user" == "root" && "$count" -gt 0 ]]; then
    echo "Root with items"
fi

if [[ "$env" == "prod" || "$env" == "staging" ]]; then
    echo "Non-local environment"
fi

# case statement — cleaner than long if/elif chains
environment="production"
case "$environment" in
    development|dev)
        echo "Dev mode"
        debug=true
        ;;
    staging)
        echo "Staging mode"
        debug=false
        ;;
    production|prod)
        echo "Production mode"
        debug=false
        ;;
    *)
        echo "Unknown environment: $environment"
        exit 1
        ;;
esac
```

## Loops

```bash
#!/usr/bin/env bash

# for loop — iterate over a list
for fruit in apple banana cherry; do
    echo "Fruit: $fruit"
done

# for loop — iterate over files
for file in /var/log/*.log; do
    echo "Processing: $file"
    gzip "$file"
done

# for loop — numeric range
for i in {1..10}; do
    echo "Iteration $i"
done

# for loop — with step
for i in {0..100..10}; do
    echo "$i"     # Prints 0, 10, 20, ..., 100
done

# C-style for loop
for ((i=0; i<10; i++)); do
    echo "Index: $i"
done

# while loop
counter=0
while [ "$counter" -lt 5 ]; do
    echo "Counter: $counter"
    counter=$((counter + 1))
done

# while loop — read file line by line
while IFS= read -r line; do
    echo "Line: $line"
done < input.txt

# until loop (opposite of while — runs UNTIL condition is true)
count=10
until [ "$count" -le 0 ]; do
    echo "Countdown: $count"
    count=$((count - 1))
done

# Loop control
for i in {1..10}; do
    if [ "$i" -eq 5 ]; then continue; fi    # Skip 5
    if [ "$i" -eq 8 ]; then break; fi       # Stop at 8
    echo "$i"
done
```

## Functions

```bash
#!/usr/bin/env bash

# Define a function
greet() {
    local name="$1"     # local = scoped to function
    local greeting="${2:-Hello}"  # Default value
    echo "$greeting, $name!"
}

# Call it
greet "Alice"
greet "Bob" "Hi"

# Return values — functions return exit codes (0–255)
is_even() {
    local number="$1"
    if (( number % 2 == 0 )); then
        return 0  # success = true
    else
        return 1  # failure = false
    fi
}

if is_even 4; then echo "4 is even"; fi
if ! is_even 7; then echo "7 is odd"; fi

# Return data via echo + command substitution
get_timestamp() {
    echo "$(date +%Y-%m-%d_%H-%M-%S)"
}

timestamp=$(get_timestamp)
echo "Script started at: $timestamp"
```

## A Complete Professional Script Example

```bash
#!/usr/bin/env bash
# =============================================================================
# Script: backup.sh
# Description: Backs up a directory with rotation
# Author: DevOps Team
# Usage: ./backup.sh <source_dir> <backup_dir> [max_backups]
# =============================================================================

set -euo pipefail

# --- Configuration ---
readonly SCRIPT_NAME=$(basename "$0")
readonly TIMESTAMP=$(date +%Y%m%d_%H%M%S)
readonly LOG_FILE="/var/log/backup.log"

# --- Colors for output ---
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'  # No Color

# --- Logging functions ---
log() { echo "[$(date +%H:%M:%S)] $*" | tee -a "$LOG_FILE"; }
success() { echo -e "${GREEN}[OK]${NC} $*"; log "OK: $*"; }
warn() { echo -e "${YELLOW}[WARN]${NC} $*"; log "WARN: $*"; }
error() { echo -e "${RED}[ERROR]${NC} $*" >&2; log "ERROR: $*"; }
die() { error "$*"; exit 1; }

# --- Validate arguments ---
usage() {
    cat << EOF
Usage: $SCRIPT_NAME <source_dir> <backup_dir> [max_backups]
  source_dir   : Directory to backup
  backup_dir   : Where to store backups
  max_backups  : Number of backups to keep (default: 7)
EOF
}

if [[ "$#" -lt 2 ]]; then
    usage
    die "Missing required arguments"
fi

SOURCE_DIR="$1"
BACKUP_DIR="$2"
MAX_BACKUPS="${3:-7}"

# --- Validation ---
[[ -d "$SOURCE_DIR" ]] || die "Source directory does not exist: $SOURCE_DIR"
[[ "$MAX_BACKUPS" =~ ^[0-9]+$ ]] || die "max_backups must be a number"

# --- Create backup directory if needed ---
mkdir -p "$BACKUP_DIR" || die "Cannot create backup directory: $BACKUP_DIR"

# --- Perform backup ---
backup_name="backup_${TIMESTAMP}.tar.gz"
backup_path="${BACKUP_DIR}/${backup_name}"

log "Starting backup of $SOURCE_DIR"
log "Destination: $backup_path"

if tar -czf "$backup_path" -C "$(dirname "$SOURCE_DIR")" "$(basename "$SOURCE_DIR")"; then
    size=$(du -sh "$backup_path" | cut -f1)
    success "Backup created: $backup_name ($size)"
else
    die "Backup failed!"
fi

# --- Rotate old backups ---
log "Rotating backups (keeping last $MAX_BACKUPS)"
backup_count=$(ls -1 "${BACKUP_DIR}"/backup_*.tar.gz 2>/dev/null | wc -l)

if [[ "$backup_count" -gt "$MAX_BACKUPS" ]]; then
    delete_count=$((backup_count - MAX_BACKUPS))
    ls -1t "${BACKUP_DIR}"/backup_*.tar.gz | tail -n "$delete_count" | while read -r old_backup; do
        rm -f "$old_backup"
        warn "Removed old backup: $(basename "$old_backup")"
    done
fi

success "Backup completed successfully"
exit 0
```

## Pro Tips — Scripting

```bash
# Debug a script
bash -x script.sh           # Print each command before executing (trace)
bash -n script.sh           # Dry run — check syntax without running
set -x                      # Enable trace within script
set +x                      # Disable trace

# Use shellcheck — THE linter for bash scripts
# Install: sudo apt install shellcheck
shellcheck script.sh        # Catches bugs before you run it

# Trap errors and cleanup on exit
trap 'cleanup' EXIT         # Run cleanup() when script exits (any reason)
trap 'cleanup' INT TERM     # Also catch Ctrl+C and kill

cleanup() {
    rm -f /tmp/lockfile
    echo "Cleaned up"
}

# Prevent multiple instances with a lock file
LOCK_FILE="/tmp/$(basename "$0").lock"
if [ -f "$LOCK_FILE" ]; then
    echo "Script already running (lock: $LOCK_FILE)"
    exit 1
fi
touch "$LOCK_FILE"
trap 'rm -f "$LOCK_FILE"' EXIT
```

---

---

# SECTION 9 — ADVANCED WORKFLOW

## Shell Configuration Files

```
Shell startup order (interactive login shell):
/etc/profile → /etc/profile.d/*.sh → ~/.bash_profile → ~/.bashrc

Key files:
~/.bashrc       — Executed for interactive non-login Bash shells
~/.bash_profile — Executed for login Bash shells (source .bashrc from here)
~/.zshrc        — Zsh equivalent of .bashrc
~/.profile      — Generic (used by sh, and as fallback)
/etc/bashrc     — System-wide Bash config
/etc/environment — System-wide environment variables
```

## Customizing `.bashrc` / `.zshrc`

```bash
# =========================================================
# SAMPLE ~/.bashrc OR ~/.zshrc CONFIGURATION
# =========================================================

# --- Environment Variables ---
export EDITOR="vim"                          # Default text editor
export VISUAL="vim"                          # For programs that check $VISUAL
export PAGER="less"                          # Default pager
export LESS="-R --quit-if-one-screen"        # less options
export HISTSIZE=10000                        # In-memory history
export HISTFILESIZE=20000                    # Disk history
export HISTCONTROL=ignoredups:erasedups      # No duplicate entries
export HISTTIMEFORMAT="%F %T  "             # Timestamps in history

# Append to history file, don't overwrite
shopt -s histappend      # Bash only

# --- PATH customization ---
export PATH="$HOME/.local/bin:$HOME/bin:$PATH"
export PATH="/usr/local/go/bin:$PATH"        # Add Go binaries
export PATH="$HOME/.cargo/bin:$PATH"         # Add Rust binaries

# --- Prompt Customization (PS1) ---
# Bash prompt with color: user@host:dir$
export PS1='\[\033[1;32m\]\u@\h\[\033[0m\]:\[\033[1;34m\]\w\[\033[0m\]\$ '

# Even better — show git branch in prompt
parse_git_branch() {
    git branch 2>/dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}
export PS1='\[\033[1;32m\]\u@\h\[\033[0m\]:\[\033[1;34m\]\w\[\033[33m\]$(parse_git_branch)\[\033[0m\]\$ '

# --- Useful Functions ---
# Create directory and cd into it
mkcd() { mkdir -p "$1" && cd "$1"; }

# Extract any archive
extract() {
    case "$1" in
        *.tar.gz|*.tgz)  tar -xzf "$1" ;;
        *.tar.bz2)       tar -xjf "$1" ;;
        *.tar.xz)        tar -xJf "$1" ;;
        *.zip)           unzip "$1" ;;
        *.gz)            gunzip "$1" ;;
        *.bz2)           bunzip2 "$1" ;;
        *.rar)           unrar x "$1" ;;
        *.7z)            7z x "$1" ;;
        *)               echo "Cannot extract: $1" ;;
    esac
}

# Quick backup of a file
bak() { cp "$1" "${1}.bak.$(date +%Y%m%d)"; }

# Go up N directories
up() { local n="${1:-1}"; for _ in $(seq 1 "$n"); do cd ..; done; }
# Usage: up 3 (go up 3 levels)

# Reload shell config without restarting
reload() { source ~/.bashrc; echo "Reloaded!"; }

# Show weather
weather() { curl -s "wttr.in/${1:-}?format=3"; }
```

## Aliases — Speed Up Your Workflow

```bash
# =========================================================
# ALIASES — add to ~/.bashrc or ~/.zshrc
# =========================================================

# --- Navigation ---
alias ..='cd ..'
alias ...='cd ../..'
alias ....='cd ../../..'
alias ~='cd ~'
alias -- -='cd -'

# --- ls Improvements ---
alias ls='ls --color=auto'
alias ll='ls -lah'
alias la='ls -A'
alias lt='ls -lt'                   # Sort by time
alias lS='ls -lS'                   # Sort by size
alias tree='tree -C'                # Colorized tree

# --- Safety ---
alias rm='rm -i'                    # Always ask before deleting
alias cp='cp -i'                    # Ask before overwriting
alias mv='mv -i'                    # Ask before overwriting
alias mkdir='mkdir -pv'             # Create parents + verbose

# --- Shortcuts ---
alias c='clear'
alias h='history'
alias j='jobs -l'
alias grep='grep --color=auto'
alias egrep='egrep --color=auto'
alias fgrep='fgrep --color=auto'

# --- Useful One-Liners ---
alias myip='curl -s ifconfig.me; echo'
alias now='date +"%Y-%m-%d %H:%M:%S"'
alias week='date +%V'               # Week number
alias path='echo $PATH | tr : "\n"' # Show PATH one per line

# --- System ---
alias update='sudo apt update && sudo apt upgrade -y'  # Ubuntu/Debian
alias df='df -hT'
alias du='du -sh'
alias free='free -h'
alias meminfo='cat /proc/meminfo | grep -i mem'
alias cpuinfo='lscpu | grep -E "^(Architecture|CPU|Thread|Core|Socket|Model name)"'

# --- Network ---
alias ports='ss -tulpn'
alias listening='ss -tlnp'

# --- Git (most-used) ---
alias g='git'
alias gs='git status'
alias ga='git add'
alias gc='git commit'
alias gp='git push'
alias gl='git pull'
alias glog='git log --oneline --graph --decorate --all'
alias gd='git diff'
alias gb='git branch'

# --- Docker ---
alias dk='docker'
alias dkps='docker ps'
alias dkpsa='docker ps -a'
alias dki='docker images'
alias dkrm='docker rm'
alias dkrmi='docker rmi'

# Apply changes without restarting terminal
# source ~/.bashrc
```

## `tmux` — Terminal Multiplexer

`tmux` keeps sessions alive after disconnection and lets you split your terminal into multiple panes.

```
tmux Architecture:
┌─────────────────────────────────────────────────┐
│  SERVER (runs in background, survives logout)   │
│  ├── SESSION 1 (e.g., "work")                   │
│  │   ├── WINDOW 1 (e.g., "code")                │
│  │   │   ├── PANE 1 (editor)                    │
│  │   │   └── PANE 2 (terminal)                  │
│  │   └── WINDOW 2 (e.g., "logs")                │
│  │       └── PANE 1                             │
│  └── SESSION 2 (e.g., "deploy")                 │
└─────────────────────────────────────────────────┘
```

```bash
# Starting tmux
tmux                                # New session (unnamed)
tmux new -s mysession               # New named session
tmux ls                             # List sessions
tmux attach -t mysession            # Attach to session
tmux attach                         # Attach to last session
tmux kill-session -t mysession      # Kill a session

# ALL tmux commands start with PREFIX (default: Ctrl+B)
# Press Ctrl+B, release, then press the key

# Sessions
PREFIX + d          # Detach from session (session keeps running!)
PREFIX + s          # List/switch sessions interactively
PREFIX + $          # Rename current session

# Windows (like tabs)
PREFIX + c          # Create new window
PREFIX + n          # Next window
PREFIX + p          # Previous window
PREFIX + [0-9]      # Switch to window by number
PREFIX + ,          # Rename window
PREFIX + w          # List windows interactively
PREFIX + &          # Kill window

# Panes (splits)
PREFIX + %          # Split vertical (left/right)
PREFIX + "          # Split horizontal (top/bottom)
PREFIX + [arrow]    # Move between panes
PREFIX + z          # Zoom pane (full screen toggle)
PREFIX + x          # Kill pane
PREFIX + q          # Show pane numbers
PREFIX + {          # Move pane left
PREFIX + }          # Move pane right
PREFIX + Space      # Cycle through pane layouts

# Copy mode (scroll and copy)
PREFIX + [          # Enter copy mode (use arrow keys to scroll)
q                   # Exit copy mode
Space               # Start selection
Enter               # Copy selection
PREFIX + ]          # Paste

# Customizing tmux (~/.tmux.conf)
# Example: change prefix to Ctrl+A (screen-style)
# set -g prefix C-a
# unbind C-b
# bind C-a send-prefix

# Mouse support
# set -g mouse on

# Apply config without restart
PREFIX + :source-file ~/.tmux.conf
```

## `screen` — Alternative Multiplexer

```bash
screen                      # New session
screen -S myname            # Named session
screen -ls                  # List sessions
screen -r myname            # Reattach
# Ctrl+A, d — detach
# Ctrl+A, c — new window
# Ctrl+A, n/p — next/previous window
# Ctrl+A, [ — scroll mode
```

## Environment Variables

```bash
# View environment
env                         # All environment variables
printenv PATH               # Specific variable
echo $HOME                  # User home directory
echo $USER                  # Current user
echo $SHELL                 # Current shell
echo $PWD                   # Current directory (same as pwd)
echo $OLDPWD                # Previous directory
echo $TERM                  # Terminal type
echo $LANG                  # Locale setting

# Set environment variable
export MY_VAR="value"       # Available to child processes
MY_VAR="value"              # Only in current shell, NOT exported

# Temporary — for one command only
MY_VAR="test" python3 script.py     # MY_VAR available only to this script

# Unset
unset MY_VAR

# Persist across sessions — add to ~/.bashrc:
# export DATABASE_URL="postgresql://localhost/mydb"
# export API_KEY="your-key-here"
```

## Productivity Tools and Workflow

```bash
# fzf — Fuzzy Finder (INSTALL THIS — it transforms your workflow)
# Install: sudo apt install fzf
history | fzf               # Fuzzy search your history
ls | fzf                    # Fuzzy pick a file
find . | fzf                # Fuzzy find any file
# Ctrl+R in shell → fuzzy history search (after fzf install)

# z — Jump around (tracks frequent directories)
# Install: https://github.com/rupa/z
z docs                      # Jump to most-used directory matching "docs"
z pro src                   # Jump to most-used dir matching "pro" AND "src"

# bat — better cat with syntax highlighting
# Install: sudo apt install bat
bat file.py                 # cat with syntax highlighting + line numbers

# ripgrep (rg) — faster grep
# Install: sudo apt install ripgrep
rg "TODO" ./src/            # Like grep -r but faster and smarter
rg -i "error" --type py     # Search only Python files

# fd — faster find
# Install: sudo apt install fd-find
fd "*.log" /var/            # Find .log files (simpler than find)
fd -t f -e py               # Find Python files
fd "config" --type f        # Find files named config

# Keyboard shortcuts in Bash/Zsh (readline)
Ctrl+A      # Jump to beginning of line
Ctrl+E      # Jump to end of line
Ctrl+K      # Delete to end of line
Ctrl+U      # Delete to beginning of line
Ctrl+W      # Delete previous word
Alt+B       # Move back one word
Alt+F       # Move forward one word
Ctrl+R      # Reverse search history (type to search)
Ctrl+G      # Cancel reverse search
Ctrl+L      # Clear screen (like 'clear')
Ctrl+Z      # Suspend current job
Ctrl+C      # Kill current job
!!          # Repeat last command
!$          # Last argument of previous command
!*          # All arguments of previous command
!n          # Run command #n from history
!foo        # Run last command starting with "foo"
```

## Pro Tips — Advanced Workflow

```bash
# Quickly edit and re-run last command
fc                          # Open last command in $EDITOR, run on save

# Parameter expansion tricks
filename="report.2025.tar.gz"
echo "${filename%%.*}"      # report          (remove longest from end)
echo "${filename%.*}"       # report.2025.tar (remove shortest from end)
echo "${filename#*.}"       # 2025.tar.gz     (remove shortest from start)
echo "${filename##*.}"      # gz              (remove longest from start)
echo "${filename/tar/TAR}"  # report.2025.TAR.gz (replace first match)
echo "${#filename}"         # 19              (string length)
echo "${filename^^}"        # REPORT.2025.TAR.GZ (uppercase)
echo "${filename,,}"        # report.2025.tar.gz (lowercase)

# Run a command when a file changes
while inotifywait -e modify file.txt; do
    echo "File changed! Running tests..."
    make test
done

# Benchmark a command
time find / -name "*.conf" 2>/dev/null

# Measure command frequency
history | awk '{print $2}' | sort | uniq -c | sort -rn | head -20
# Shows your 20 most-used commands — tells you what to alias

# Create a persistent alias on the fly and apply it
echo "alias myalias='my_long_command'" >> ~/.bashrc && source ~/.bashrc
```

---

---

# QUICK REFERENCE CHEAT SHEET

```
┌────────────────────────────────────────────────────────────────────┐
│                    ESSENTIAL CLI CHEAT SHEET                       │
├────────────────────────────┬───────────────────────────────────────┤
│ NAVIGATION                 │ PERMISSIONS                           │
│  pwd / cd / ls -lah        │  chmod 755 / chmod u+x               │
│  cd - (prev dir)           │  chown user:group file               │
│  find / locate             │  ls -l (view perms)                  │
├────────────────────────────┼───────────────────────────────────────┤
│ FILES                      │ PROCESSES                             │
│  cp -r / mv / rm -rf       │  ps aux / top / htop                 │
│  ln -s (symlink)           │  kill PID / kill -9 PID              │
│  tar -czf / tar -xzf       │  nohup cmd & / jobs / fg / bg        │
├────────────────────────────┼───────────────────────────────────────┤
│ TEXT PROCESSING            │ NETWORKING                            │
│  grep -rn / grep -v        │  curl -s / wget -O                   │
│  sed 's/old/new/g' -i      │  ssh user@host / scp                 │
│  awk -F: '{print $1}'      │  ss -tulpn / ping / dig              │
├────────────────────────────┼───────────────────────────────────────┤
│ I/O STREAMS                │ PRODUCTIVITY                          │
│  cmd > file (overwrite)    │  Ctrl+R (history search)             │
│  cmd >> file (append)      │  !! (repeat last cmd)                │
│  cmd 2>/dev/null           │  !$ (last argument)                  │
│  cmd1 | cmd2 (pipe)        │  tmux new/attach/detach              │
│  tee (pipe + save)         │  alias ll='ls -lah'                  │
└────────────────────────────┴───────────────────────────────────────┘

OCTAL PERMISSIONS:  7=rwx  6=rw-  5=r-x  4=r--  0=---
COMMON PATTERNS:    644=files  755=dirs/scripts  600=private  700=private dir

SIGNAL NUMBERS:     1=HUP(reload)  2=INT(Ctrl+C)  9=KILL(force)  15=TERM(graceful)
```

---

# LEARNING PATH ROADMAP

```
BEGINNER (Week 1–2)
├── Navigate the filesystem (pwd, cd, ls)
├── Create/copy/move/delete files
├── Read files (cat, less, head, tail)
├── Basic grep usage
└── Understand permissions (ls -l, chmod)

INTERMEDIATE (Week 3–6)
├── Pipe commands together
├── Redirect I/O (>, >>, 2>&1)
├── find and locate
├── sed and basic awk
├── Process management (ps, kill, jobs)
├── Write basic shell scripts
└── SSH into remote machines

ADVANCED (Month 2–3)
├── Complex awk data processing
├── Professional shell scripting (functions, error handling)
├── Network tools (curl, netstat, nmap)
├── tmux workflow
├── .bashrc customization and aliases
├── Performance monitoring
└── Security (permissions, ACLs, SSH keys)

PROFESSIONAL (Month 3+)
├── Systemd services
├── Log analysis pipelines
├── Cron jobs and scheduling
├── sed/awk one-liners
├── Container CLI (Docker, Podman)
├── Cloud CLI (AWS, GCP, Azure)
└── Infrastructure as Code (Terraform, Ansible)
```

---

*Last updated: 2025 | Author: Senior SysAdmin & DevOps Engineer*
*Save this file as `CLI_Master_Guide.md` for offline reference.*
