# k1 — Orientation: What “Linux” Means Across Distros 🧭

Goals (what you’ll be able to do after this chapter)

1. <span>Explain what a </span>**Linux distribution**<span> is—and what parts are </span>**the same**<span> everywhere.</span>
2. Recognize the main “families” (Debian/Ubuntu vs RHEL/Rocky/Alma) and why that matters.
3. <span>Choose a </span>**safe practice setup**<span> (VM/SSH/container) without “committing” to one distro.</span>
4. Build a mental model for what changes across distros (so you don’t get surprised later).

# [Overview] k1 — Orientation: What “Linux” Means Across Distros 🧭

## 1.1 Distributions &amp; families

### What “Linux” usually means in practice

When people say “Linux,” they often mean an entire operating system stack:

- **Linux kernel** (the core: hardware, processes, memory, networking)
- **Userland tools** (GNU coreutils like `ls`, `cp`, `grep`, `tar`, etc.)
- **Init/service manager** (commonly **systemd** today)
- **Package manager + repositories** (how software is installed/updated)
- **Default configs** and security policies

A **distribution (distro)** is a curated bundle of those pieces with a particular philosophy (stability vs newness), defaults, and packaging.

### The two big server families you’ll meet most

1. **Debian family**
    
    
    - **Debian** (very stability-focused)
    - **Ubuntu** (based on Debian; popular; Ubuntu **LTS** is common on servers)
2. **RHEL family** (Red Hat Enterprise Linux–compatible)
    
    
    - **Rocky Linux**, **AlmaLinux** (common on “enterprise-style” servers)
    - Historically CentOS filled this role

✅ **What’s shared across both:** filesystem concepts, permissions, SSH, networking basics, processes, most command-line tools, and the general “shape” of running a web server.

---

## 1.2 What differs (and why it matters)

Here’s the “difference map” you’ll keep using throughout the course:

1. **Package management**
    
    
    - Debian/Ubuntu: `apt`
    - Rocky/Alma: `dnf` (and sometimes legacy `yum`)
    - Practical impact: different commands, sometimes different package names, and sometimes different “recommended” installation methods.
2. **Release cadence (how fast things change)**
    
    
    - Debian stable / RHEL-like: slower-moving, long lifecycle
    - Ubuntu LTS: stable, but often newer than Debian stable
    - Practical impact: versions of PHP, Nginx, Node, etc. available via default repos.
3. **Security frameworks &amp; defaults**
    
    
    - RHEL family: **SELinux** is a major factor
    - Ubuntu: **AppArmor** is common
    - Practical impact: the same config can “work” on one distro but get blocked by MAC policies on another until you learn to diagnose it.
4. **Default tooling and conventions**
    
    
    - Firewall tools: often **UFW** (Ubuntu) vs **firewalld** (RHEL family)
    - Log locations and config paths are *mostly* similar, but defaults can differ.
    - Practical impact: you’ll learn to *find* the right file/service rather than memorize one path.

💡 Key mindset: **Learn the core once, then learn the “translation layer.”** This course is structured exactly that way.

---

## 1.3 Your working environment (local vs server)

You’ll typically interact with Linux in one of these modes:

1. **Local Linux** (installed on your machine)
    
    
    - Best if you want Linux as your daily driver.
    - Not required for learning server ops.
2. **VMs (recommended for learning)**
    
    
    - Run Debian/Ubuntu/Rocky/Alma as virtual machines and break/fix safely.
    - Works great with snapshots.
3. **Remote servers (VPS/cloud)**
    
    
    - Realistic: public IP, SSH, DNS, firewall, actual deployment constraints.
    - Higher stakes if you misconfigure something.
4. **Containers**
    
    
    - Great for reproducible app environments (Node/React, services).
    - Not a full “OS admin” experience by itself (containers share the host kernel).

### My recommended practice setup for you (web dev + WordPress)

- **One VM** as your “sandbox server”
- **One cheap VPS later** (optional) to practice real-world networking/TLS
- Add **containers** once you start Node/React workflows

---

## 1.4 Safety &amp; learning workflow

### The “don’t regret it later” rules

1. **Always have a rollback**
    
    
    - Use VM snapshots before major changes.
    - Keep copies of config files before editing (even a simple `cp file file.bak`).
2. **Make changes intentionally**
    
    
    - Change *one thing at a time*.
    - Keep a small change log for yourself (what you did + why).
3. **Practice in layers**
    
    
    - First: command line + files + permissions
    - Then: services + logs
    - Then: networking + firewall
    - Then: web stack + TLS

### Tools you’ll likely use

- **SSH** for remote access
- A terminal editor (**nano** or minimal **vim** skills)
- A way to snapshot/clone environments (VM snapshots; later Docker images)

---

## Mini roadmap: what’s next 🔭

1. **k2** makes you comfortable in the shell (portable across distros).
2. **k3** teaches filesystems + permissions (critical for WordPress security and debugging).
3. Later chapters introduce the **translation layer** (APT vs DNF, UFW vs firewalld, AppArmor vs SELinux).

---

### Quick check-in (optional, to tailor future lessons)

What will you use first for practice: **VM**, **a VPS**, or **WSL/macOS terminal + remote server**?

# k1.1 — Distributions & Families: What “Linux” Is (and Isn’t) 🌍

### What people mean when they say “Linux”

In everyday dev/admin talk, “Linux” usually refers to an *entire operating system stack*, not just one component:

1. **Linux kernel**  
    The core that handles:
    
    
    - processes and scheduling
    - memory management
    - networking
    - hardware drivers
2. [**Userland tools**](https://wiki.fabula.vision/books/linux/page/common-linux-command-line-tools-portable-across-distros "Common Linux Command-Line Tools (Portable Across Distros) 🧰")  
    The standard command-line tools you’ll use constantly, such as:
    
    
    - `ls`, `cp`, `mv`, `rm`, `find`
    - `grep`, `sed`, `awk`
    - `tar`, `ssh`, `curl`
3. **Init / service manager**  
    On most modern distros, this is **systemd** (so services behave similarly across many distributions).
4. **Package manager + repositories**  
    How software is installed and updated (this is one of the biggest practical differences across distros).
5. **Defaults &amp; policies**  
    Security frameworks, filesystem defaults, preinstalled tools, and “the distro’s way” of doing common tasks.

---

### What a “distribution” actually is

A **Linux distribution (distro)** is a curated bundle of the components above, plus:

- a release philosophy (stable vs fast-moving)
- a packaging system and official repositories
- default configuration choices
- documentation/community norms

So you’re not learning a completely different OS each time—you’re learning **the same core concepts** with different “packaging and defaults.”

---

### The main families you’ll encounter (server/web world)

For web development and WordPress hosting, these families matter most:

1. **Debian family**
    
    
    - **Debian** (very stability-focused, conservative updates)
    - **Ubuntu** (based on Debian; very common, especially **Ubuntu LTS** on servers)
    - Typical traits: 
        - uses **APT** (`apt`)
        - huge ecosystem of tutorials and packages
2. **RHEL family** (Red Hat Enterprise Linux–compatible)
    
    
    - **Rocky Linux**, **AlmaLinux** (common for enterprise-style servers and some tooling stacks)
    - Typical traits: 
        - uses **DNF** (`dnf`, historically `yum`)
        - **SELinux** is commonly enabled and relevant

---

### What’s shared across most distros (the “learn once” core)

If you learn these well, you can function on almost any mainstream Linux server:

- filesystem concepts and common directories (you’ll cover this in **k3**)
- permissions and ownership (`chmod`, `chown`)
- processes and signals (`ps`, `kill`)
- service management concepts (often via `systemctl`)
- networking basics (ports, DNS, `curl`, `ss`)
- SSH and key-based access

---

### What this means for your course goal

Your plan—**learn cross-distro fundamentals first without committing**—works because:

- the *core Linux skills* transfer extremely well
- later, you mainly “translate”: 
    - `apt` ↔ `dnf`
    - AppArmor ↔ SELinux
    - UFW ↔ firewalld
    - slightly different defaults/paths

---

### Tiny self-check ✅

Answer these without Googling (it’s fine if you can’t yet):

1. What’s the **kernel** responsible for (in one sentence)?
2. Name **two things** that are usually different between Debian-based and RHEL-based distros.
3. What’s one Linux skill that should transfer across almost all distros?

If you want, reply with your answers and I’ll correct/clarify briefly.

# Common Linux Command-Line Tools (Portable Across Distros) 🧰

Below is a **practical, cross‑distro** “core toolbox” of commands you’ll use constantly. I’ll group them by job, give a **plain meaning**, and include **examples** you can try.

> Notes:
> 
> - Examples assume a typical Bash-like shell.
> - Many commands have lots of options—this is the “most useful baseline.”

---

## 1) Getting oriented (where am I? what’s here?)

### `pwd` — print working directory

Shows your current directory.

```bash
pwd
# /home/alex/projects
```

### `ls` — list directory contents

```bash
ls
ls -l        # long listing (permissions, owner, size, time)
ls -a        # include hidden files (dotfiles)
ls -lah      # long + all + human-readable sizes
```

### `cd` — change directory

```bash
cd /etc
cd ..        # up one directory
cd ~         # home directory
cd -         # previous directory
```

### `tree` — show directory tree (often needs installing)

```bash
tree
tree -L 2    # limit depth
```

---

## 2) Creating, moving, copying, deleting (file operations)

### `touch` — create an empty file / update timestamp

```bash
touch notes.txt
```

### `mkdir` — make directories

```bash
mkdir logs
mkdir -p a/b/c   # create parents as needed
```

### `cp` — copy files/directories

```bash
cp a.txt b.txt
cp -r src/ backup-src/     # copy directory recursively
cp -a src/ backup-src/     # archive mode: preserve permissions/times (very common)
```

### `mv` — move/rename files/directories

```bash
mv oldname.txt newname.txt
mv file.txt /tmp/
```

### `rm` — remove files/directories (destructive)

```bash
rm file.txt
rm -r folder/       # recursive delete directory
rm -rf folder/      # force + recursive (use extreme caution)
```

### `ln` — create links (symlinks are very common)

```bash
ln -s /var/www/site/current/public public   # symlink
```

---

## 3) Reading files quickly

### `cat` — print file contents

Good for small files; for big ones prefer `less`.

```bash
cat /etc/hostname
```

### `less` — page through text interactively

Keys: `q` quit, `/text` search, `n` next match.

```bash
less /var/log/syslog
```

### `head` / `tail` — show start/end of file

```bash
head -n 20 access.log
tail -n 50 error.log
tail -f error.log     # follow appended log lines (real-time)
```

### `nl` — show file with line numbers

```bash
nl -ba nginx.conf
```

---

## 4) Help &amp; discovery

### `man` — manual pages

```bash
man ls
man -k network    # search man page descriptions (keyword)
```

### `--help` — quick built-in help (common convention)

```bash
grep --help
```

### `which` / `type` — where a command comes from

```bash
which python
type ls            # also tells if it’s an alias/function/builtin
```

---

## 5) Searching text (the everyday “find inside files” tools)

### `grep` — search text for patterns

```bash
grep "listen" nginx.conf
grep -R "DB_HOST" .           # recursive search
grep -n "error" app.log        # include line numbers
grep -i "warning" app.log      # case-insensitive
```

### `sed` — stream editor (common for simple substitutions)

```bash
sed 's/http:/https:/g' urls.txt
sed -n '1,20p' file.txt        # print specific lines
```

<details id="bkmrk-sed-%F0%9F%A4%96-sed-is-a-strea"><summary>sed</summary>

🤖 `sed` is a **stream editor**: it reads text **one line at a time**, applies one or more editing “commands” you give it, and then (by default) **prints the result**. It’s especially useful in pipelines because it can transform text *as it flows through*—without you opening an editor. 🛠️

1. **How** `sed` **thinks (the mental model)**
    
    
    1. `sed` takes input from:
        
        
        - a file: `sed '...' file.txt`
        - *or* stdin (a pipe): `some_command | sed '...'`
    2. For each line, it:
        
        
        - loads the line into a temporary buffer (often called the *pattern space*)
        - runs your commands on that line
        - prints the line (unless you tell it not to)
2. **The most common command: substitution (**`s/…/…/`**)**  
    The form is:
    
    ```bash
    sed 's/PATTERN/REPLACEMENT/FLAGS'
    ```
    
    Example from your notes:
    
    ```bash
    sed 's/http:/https:/g' urls.txt
    ```
    
    What it means:
    
    
    - `s` = “substitute”
    - `http:` = the text (or regex) to find
    - `https:` = what to replace it with
    - `g` = “global” on the line (replace **all** matches in that line, not just the first)
    
    Concrete example:
    
    
    - Input line: [`http://a`](http://a)` `[`http://b`](http://b)
    - Without `g` (`sed 's/http:/https:/'`): [`https://a`](https://a)` `[`http://b`](http://b)
    - With `g` (`sed 's/http:/https:/g'`): [`https://a`](https://a)` `[`https://b`](https://b)
3. **Patterns are usually regular expressions (regex)**  
    `sed` patterns are typically regex, so you can match more than literal text.
    
    
    - Replace any run of spaces with one space:
        
        ```bash
        echo "a     b" | sed 's/  */ /g'
        ```
    - Replace only at the start of the line using `^`:
        
        ```bash
        echo "ERROR: bad" | sed 's/^ERROR:/WARN:/'
        ```
    - Replace only at the end using `$`:
        
        ```bash
        echo "file.tmp" | sed 's/\.tmp$/.txt/'
        ```
    
    Notes:
    
    
    - In basic `sed`, some regex operators need escaping (like `\+` instead of `+`). On many systems you can use extended regex with `-E`:
        
        ```bash
        echo "a     b" | sed -E 's/ +/ /g'
        ```
4. **Printing vs suppressing output (**`-n` **and** `p`**)**  
    By default, `sed` prints every (possibly modified) line. If you only want *some* lines, use `-n` (no auto-print) plus `p` (print).
    
    Your example:
    
    ```bash
    sed -n '1,20p' file.txt
    ```
    
    Meaning:
    
    
    - `-n` = don’t print everything automatically
    - `1,20p` = print only lines 1 through 20
    
    Similarly, to print only lines that match a pattern:
    
    ```bash
    sed -n '/error/p' app.log
    ```
5. **Filtering/deleting lines (**`d`**)**  
    Another very common use is deleting lines (i.e., filtering them out).
    
    
    - Delete blank lines:
        
        ```bash
        sed '/^$/d' file.txt
        ```
    - Delete comment lines starting with `#`:
        
        ```bash
        sed '/^#/d' file.txt
        ```
6. **In-place editing (**`-i`**)—powerful but easy to misuse**  
    If you want to actually modify a file on disk (instead of just printing to the terminal), you can use `-i`.
    
    
    - Replace in a file *in place*:
        
        ```bash
        sed -i 's/old/new/g' config.txt
        ```
    
    Many people prefer making a backup:
    
    ```bash
    sed -i.bak 's/old/new/g' config.txt
    ```
    
    That will leave `config.txt.bak` behind as a safety net.
7. **Putting it in pipelines (why it’s called a “stream” editor)**  
    `sed` shines when transforming command output:
    
    ```bash
    ps aux | sed -n '1,5p'
    ```
    
    Or when cleaning data before feeding it to something else:
    
    ```bash
    cat access.log | sed 's/"//g' | cut -d' ' -f1 | sort | uniq -c | sort -nr
    ```

If you tell me what exactly felt unclear (e.g., the `s///g` syntax, regex characters, or `-n ... p`), I can tailor a few examples directly to your kind of files/logs.

</details>### `awk` — field/column processing

```bash
awk '{print $1, $9}' access.log   # e.g., IP and status code columns (depends on log format)
```

---

## 6) Counting, sorting, unique-ing (text pipelines)

### `wc` — count lines/words/bytes

```bash
wc -l access.log     # number of lines
```

### `sort` — sort lines

```bash
sort names.txt
sort -n numbers.txt  # numeric sort
```

### `uniq` — collapse adjacent duplicates (usually used after `sort`)

```bash
sort users.txt | uniq
sort users.txt | uniq -c | sort -nr   # frequency count, descending
```

### `cut` — extract columns/fields

```bash
cut -d: -f1 /etc/passwd     # usernames (field 1, delimiter ':')
```

### `tr` — translate/delete characters

```bash
tr '[:lower:]' '[:upper:]' < file.txt
```

---

## 7) Composing commands (pipes, redirection, and “do this to each line”)

### `|` (pipe) — send output of one command into another

```bash
ps aux | grep nginx
```

### Redirection: `>`, `>>`, `2>`, `&>`

```bash
echo "hello" > out.txt      # overwrite
echo "more"  >> out.txt     # append
cmd 2> err.txt              # stderr to file
cmd &> all.txt              # stdout+stderr to file (bash)
```

### `tee` — write output to file *and* keep showing it

```bash
echo "config" | tee -a notes.txt
```

### `xargs` — turn input lines into arguments (batch operations)

```bash
find . -name "*.log" | xargs rm -f
# safer form when filenames may contain spaces:
find . -name "*.log" -print0 | xargs -0 rm -f
```

---

## 8) Finding files

### `find` — search by name/type/time/size (very common)

```bash
find . -name "*.conf"
find /var/log -type f -mtime -7     # files modified in last 7 days
find . -type f -size +100M          # larger than 100MB
```

### `locate` — fast filename search via database (needs updated index)

```bash
locate nginx.conf
```

---

## 9) Permissions &amp; ownership (you’ll use these constantly on servers)

### `chmod` — change permissions

```bash
chmod 644 file.txt    # rw-r--r--
chmod 755 script.sh   # rwxr-xr-x
chmod -R 755 public/  # recursively (use carefully)
```

### `chown` / `chgrp` — change owner / group

```bash
chown www-data:www-data -R /var/www/site
chgrp developers project/
```

### `umask` — default permission mask for new files

```bash
umask
```

---

## 10) Processes &amp; system state (baseline diagnostics)

### `ps` — show processes

```bash
ps aux
ps aux | grep php-fpm
```

### `top` / `htop` — live process viewer (`htop` may need install)

```bash
top
htop
```

### `kill` / `pkill` — send signals to processes

```bash
kill 1234
pkill nginx
kill -TERM 1234   # graceful request
kill -KILL 1234   # force (last resort)
```

### `systemctl` — manage services (systemd systems)

```bash
systemctl status nginx
systemctl restart nginx
systemctl enable nginx   # start on boot
```

### `journalctl` — systemd logs

```bash
journalctl -u nginx
journalctl -u nginx -f       # follow
journalctl -b                # logs since boot
```

---

## 11) Networking essentials (developer/server workflow)

### `ip` — network interfaces and routes

```bash
ip a          # addresses
ip r          # routes
```

### `ss` — see listening ports and connections

```bash
ss -tulpn     # TCP/UDP listening + process names
```

### `ping` — basic reachability test

```bash
ping -c 4 example.com
```

### `curl` — make HTTP requests (huge for web debugging)

```bash
curl https://example.com
curl -I https://example.com          # headers only
curl -v https://example.com          # verbose (TLS + connection details)
```

### `dig` / `nslookup` — DNS queries (often `dig`)

```bash
dig example.com A
dig example.com +short
```

---

## 12) Archives &amp; compression (moving code, backups)

### `tar` — create/extract tar archives (the Linux standard)

```bash
tar -czf site.tar.gz site/     # create gzip-compressed archive
tar -xzf site.tar.gz           # extract
```

### `gzip` / `xz` — compression tools (often used via `tar`)

```bash
gzip large.log
xz -T0 bigfile     # stronger compression; -T0 uses all cores
```

### `zip` / `unzip` — common for cross-platform bundles

```bash
zip -r project.zip project/
unzip project.zip
```

---

## 13) Remote access &amp; file transfer (core server skills)

### `ssh` — remote shell

```bash
ssh user@server.example.com
ssh -i ~/.ssh/id_ed25519 user@server
```

### `scp` — copy over SSH (simple, not always the best)

```bash
scp file.txt user@server:/tmp/
scp -r site/ user@server:/var/www/
```

### `sftp` — interactive file transfer over SSH

```bash
sftp user@server
# then: put/get, ls, cd, etc.
```

---

## 14) Privilege escalation (admin work)

### `sudo` — run as root (or another user)

```bash
sudo apt update
sudo systemctl restart nginx
```

---

## 15) “Environment” and shell basics you’ll constantly touch

### `echo` — print text / variables

```bash
echo "Hello"
echo "$HOME"
```

### `env` / `printenv` — show environment variables

```bash
env
printenv PATH
```

### `export` — set environment variable for this shell session

```bash
export NODE_ENV=production
```

### `history` — show command history

```bash
history | tail
```

---

### If you want, I can turn this into a printable “cheat sheet”

Tell me your target context: **web server admin (WordPress)**, **Node/React dev**, or **general Linux**—and whether you’re on **Debian-like** or **RHEL-like** most often.

# Anki Cloze Cards — Common Linux Command-Line Tools 🧰

Below are **Anki cloze (deletion) notes** you can paste into Anki (note type: **Cloze**).  
Each note has **1–4 blanks** and is designed to be *memorable*, *practical*, and *cross‑distro*. ✅  
I also added a **few high-value extras** (e.g., `du`, `df`, `chmod` meaning, safer `find`, `rsync`, `ssh` tips) that fit perfectly with the topic.

---

## 1) Orientation &amp; navigation 🧭

1. `pwd` prints the {{c1::current working directory}}.
2. `ls -l` shows a {{c1::long listing}} (permissions, owner, size, time).
3. `ls -a` includes {{c1::hidden files (dotfiles)}}.
4. `ls -lah` combines {{c1::-l}}, {{c2::-a}}, and {{c3::human-readable sizes (-h)}}.
5. `cd ..` goes {{c1::up one directory}}.
6. `cd ~` goes to your {{c1::home directory}}.
7. `cd -` switches to the {{c1::previous directory}}.
8. `tree -L 2` shows a directory tree limited to {{c1::depth 2}}. *(Often needs installing.)*
9. To display your username and hostname quickly: `{{c1::whoami}}` and `{{c2::hostname}}`. *(Extra, useful baseline.)*

---

## 2) Create / move / copy / delete (file ops) 📁

10. `touch file.txt` {{c1::creates an empty file}} or {{c2::updates its timestamp}}.
11. `mkdir -p a/b/c` creates directories {{c1::including parents as needed}}.
12. `cp a.txt b.txt` {{c1::copies a file}}.
13. `cp -r src/ dst/` copies a directory {{c1::recursively}}.
14. `cp -a src/ dst/` uses {{c1::archive mode}} to preserve {{c2::permissions and timestamps}}.
15. `mv old new` {{c1::renames}} or {{c2::moves}} files/directories.
16. `rm -r folder/` deletes a directory {{c1::recursively}}.
17. `rm -rf folder/` means {{c1::recursive}} + {{c2::force}} → {{c3::dangerous (no prompts)}}.
18. `ln -s TARGET LINKNAME` creates a {{c1::symbolic link (symlink)}}.
19. A **hard link** shares the same {{c1::inode}} as the original file; a symlink stores a {{c2::path}}. *(Extra but core concept.)*
20. Use `rm -i` for {{c1::interactive confirmation}} (safer deletes). *(Extra.)*

---

## 3) Reading files fast 👀

21. `cat` is best for {{c1::small files}}; for big files prefer {{c2::less}}.
22. In `less`, `q` {{c1::quits}}, `/text` {{c2::searches}}, and `n` jumps to {{c3::next match}}.
23. `head -n 20 file` shows the {{c1::first 20 lines}}.
24. `tail -n 50 file` shows the {{c1::last 50 lines}}.
25. `tail -f` {{c1::follows appended lines}} (great for logs).
26. `nl -ba file` shows line numbers; `-b a` means number {{c1::all lines}} (including blank). *(Good to remember.)*
27. Quick “watch a file change” tool: `{{c1::watch}} -n 1 'tail -n 20 file'`. *(Extra.)*

---

## 4) Help &amp; discovery 🔎

28. `man ls` opens the command’s {{c1::manual page}}.
29. `man -k network` performs a {{c1::keyword search}} (apropos).
30. Many commands support `--help` for {{c1::quick usage info}}.
31. `which python` prints the {{c1::path}} to the executable found in `PATH`.
32. `type ls` can reveal whether `ls` is an {{c1::alias}}, {{c2::function}}, {{c3::builtin}}, or external command.
33. Use `{{c1::command -v}} name` for a portable “where is it?” check. *(Extra, common in scripts.)*

---

## 5) Searching inside files (grep/sed/awk) 🧠

34. `grep "listen" nginx.conf` searches for the {{c1::literal pattern}} in a file.
35. `grep -R "DB_HOST" .` searches {{c1::recursively}} in the current directory.
36. `grep -n "error" app.log` includes {{c1::line numbers}}.
37. `grep -i "warning" app.log` is {{c1::case-insensitive}}.
38. `grep -v PATTERN` prints lines that {{c1::do NOT match}}. *(Extra.)*
39. `grep -E` enables {{c1::extended regex}} (like `+`, `|`, `()` without heavy escaping). *(Extra.)*
40. `sed 's/OLD/NEW/g' file` does a substitution; `g` means {{c1::replace all matches per line}}.
41. `sed -n '1,20p' file` uses `-n` to {{c1::suppress auto-print}} and `p` to {{c2::print selected lines}}.
42. In regex, `^` matches {{c1::start of line}} and `\$` matches {{c2::end of line}}.
43. `sed '/^$/d' file` deletes lines that are {{c1::blank}}.
44. `sed -i.bak 's/old/new/g' file` edits {{c1::in place}} while keeping a {{c2::backup}}.
45. In `awk '{print \$1, \$9}'`, `\$1` is the {{c1::first field}} and `\$9` the {{c2::ninth field}}.
46. `awk -F: '{print \$1}' /etc/passwd` sets the field separator to {{c1::`:`}}. *(Extra, highly practical.)*
47. `awk 'NR==1{print}' file` uses `NR` as the {{c1::record (line) number}}. *(Extra.)*

---

## 6) Counting / sorting / unique (pipelines) 📊

48. `wc -l file` counts {{c1::lines}}.
49. `sort -n numbers.txt` performs a {{c1::numeric sort}}.
50. `uniq` only removes {{c1::adjacent duplicates}} → often use it after {{c2::sort}}.
51. `uniq -c` prefixes each group with its {{c1::count}}.
52. `sort users.txt | uniq -c | sort -nr` gives a {{c1::frequency table}} sorted {{c2::descending}}.
53. `cut -d: -f1 /etc/passwd` uses delimiter {{c1::`:`}} and prints field {{c2::1}} (usernames).
54. `tr '[:lower:]' '[:upper:]'` converts {{c1::lowercase}} to {{c2::uppercase}}.
55. `tr -d '\r'` deletes {{c1::carriage returns}} (fix Windows CRLF). *(Extra, common pain point.)*

---

## 7) Composition: pipes, redirection, tee, xargs 🧩

56. The pipe `|` sends {{c1::stdout of one command}} into {{c2::stdin of another}}.
57. `>` {{c1::overwrites}} a file, while `>>` {{c2::appends}}.
58. `2>` redirects {{c1::stderr}} to a file.
59. `&>` redirects {{c1::stdout and stderr}} to the same file (Bash).
60. `tee -a file` {{c1::appends}} while still printing to the {{c2::terminal}}.
61. `xargs` turns {{c1::input lines}} into {{c2::command arguments}}.
62. Safer filenames: `find ... -print0 | xargs -0 ...` handles {{c1::spaces/newlines}} correctly.
63. Even safer: `find ... -exec cmd {} +` avoids some {{c1::xargs pitfalls}}. *(Extra.)*

---

## 8) Finding files (find/locate) 🗂️

64. `find . -name "*.conf"` finds files by {{c1::name pattern}}.
65. `find /var/log -type f -mtime -7` finds regular files modified in the last {{c1::7 days}}.
66. `find . -type f -size +100M` finds files larger than {{c1::100 MB}}.
67. `locate nginx.conf` searches a {{c1::database index}} → results may be stale unless updated. *(Extra concept.)*
68. `find . -iname "*.jpg"` is case-{{c1::insensitive}} name matching. *(Extra.)*
69. `find . -maxdepth 1 -type f` limits search depth to {{c1::1}}. *(Extra.)*

---

## 9) Permissions &amp; ownership 🔐

70. `chmod 644 file` corresponds to {{c1::rw-r–r–}}.
71. `chmod 755 script.sh` corresponds to {{c1::rwxr-xr-x}}.
72. In permissions, `r=4`, `w=2`, `x=1`, so `7` equals {{c1::rwx}}. *(Extra, core mental model.)*
73. `chmod -R 755 dir/` changes permissions {{c1::recursively}} (use carefully).
74. `chown user:group file` changes {{c1::owner}} and {{c2::group}}.
75. `chown -R www-data:www-data /var/www/site` applies ownership changes {{c1::recursively}}.
76. `umask` affects the {{c1::default permissions}} for newly created files/dirs.
77. Typical defaults: `umask 022` leads to new files being {{c1::644}} and dirs {{c2::755}} (before special cases). *(Extra.)*

---

## 10) Processes &amp; system state 🧯

78. `ps aux` shows {{c1::all processes}} (common BSD-style format).
79. `top` provides a {{c1::live}} process view; `htop` is a more {{c2::interactive}} alternative (may need install).
80. `kill 1234` sends {{c1::SIGTERM}} by default (a polite request).
81. `kill -KILL 1234` sends {{c1::SIGKILL}} → cannot be {{c2::caught/ignored}} (last resort).
82. `pkill nginx` kills processes by {{c1::name/pattern}}.
83. `systemctl status nginx` shows {{c1::service status}} (systemd systems).
84. `systemctl enable nginx` enables start on {{c1::boot}}.
85. `journalctl -u nginx -f` follows logs for unit {{c1::nginx}} in {{c2::real time}}.
86. `journalctl -b` shows logs since the last {{c1::boot}}.
87. Check disk usage quickly: `{{c1::df -h}}` (filesystem free space) vs `{{c2::du -sh DIR}}` (directory size). *(Extra, very common.)*

---

## 11) Networking essentials 🌐

88. `ip a` shows {{c1::addresses/interfaces}}; `ip r` shows {{c2::routes}}.
89. `ss -tulpn` lists listening {{c1::TCP/UDP}} sockets with {{c2::process info}} (needs privileges for full details).
90. `ping -c 4 example.com` sends {{c1::4}} ICMP echo requests.
91. `curl -I URL` fetches only {{c1::HTTP headers}}.
92. `curl -v URL` enables {{c1::verbose}} output (connection/TLS details).
93. `dig example.com +short` returns a {{c1::short}} DNS answer list.
94. Quick port test: `{{c1::nc}} -vz host 443` (or `{{c2::curl}}` to an HTTP port). *(Extra.)*

---

## 12) Archives &amp; compression 📦

95. `tar -czf site.tar.gz site/` creates a {{c1::gzip-compressed}} tar archive.
96. `tar -xzf site.tar.gz` {{c1::extracts}} a gzip-compressed tar archive.
97. In `tar`, `c={{c1::create}}`, `x={{c2::extract}}`, `z={{c3::gzip}}`, `f={{c4::filename}}`.
98. `gzip large.log` compresses to {{c1::large.log.gz}}.
99. `xz -T0 bigfile` uses {{c1::all CPU cores}} (`-T0`) for compression.
100. `zip -r project.zip project/` creates a zip archive {{c1::recursively}}.
101. `unzip project.zip` {{c1::extracts}} a zip archive.

---

## 13) Remote access &amp; transfer (SSH family) 🔑

102. `ssh user@host` opens a {{c1::remote shell}} over SSH.
103. `ssh -i ~/.ssh/id_ed25519 user@host` uses a specific {{c1::private key}}.
104. `scp file user@host:/tmp/` copies a file over {{c1::SSH}}.
105. `sftp user@host` provides an {{c1::interactive}} file-transfer session.
106. Better large sync tool: `{{c1::rsync}} -avz SRC/ user@host:DST/` (preserves attrs, efficient). *(Extra, extremely practical.)*
107. SSH config shortcut: define a host in `{{c1::~/.ssh/config}}` to avoid retyping usernames/keys. *(Extra.)*

---

## 14) Privilege escalation 🛡️

108. `sudo cmd` runs a command as {{c1::root}} (or another user).
109. Use `sudo -u USER cmd` to run as {{c1::a specific user}}. *(Extra.)*
110. Prefer editing protected files with `{{c1::sudoedit}}` rather than running a full editor as root. *(Extra safety.)*

---

## 15) Environment &amp; shell basics 🧪

111. `echo "\$HOME"` prints the value of the {{c1::HOME}} environment variable.
112. `env` shows the process {{c1::environment}} (variables).
113. `printenv PATH` prints the {{c1::PATH}} variable.
114. `export VAR=value` sets an env var for the {{c1::current shell session}} and its {{c2::child processes}}.
115. `history | tail` shows the {{c1::most recent}} commands.
116. `VAR=value cmd` sets `VAR` only for {{c1::that command invocation}} (not permanently). *(Extra, very useful.)*

---

## 16) High-yield “extras” that pair well with the toolbox ⭐

117. To run a command as another user without a shell: `sudo -u user {{c1::--}} cmd` prevents option confusion. *(Extra nuance.)*
118. `chmod u+x script.sh` adds execute for the {{c1::user (owner)}}; symbolic modes can be clearer than octal. *(Extra.)*
119. `ls -lt` sorts by {{c1::modification time}} (newest first). *(Extra.)*
120. `sort -u` both sorts and removes duplicates in {{c1::one step}}. *(Extra.)*
121. Safer grep in binaries: `grep -I` treats binary files as {{c1::non-matching}}. *(Extra.)*
122. `curl -sS` means {{c1::silent}} but still show {{c2::errors}}. *(Extra.)*

---

### Want these as a *single “deck-ready” TSV*? 📌

Tell me your preferred import format:

1. **Plain cloze lines** (as above)
2. **TSV** with columns: `Text` + `Tags`
3. **Grouped by tags** (e.g., `linux::files`, `linux::network`, `linux::text`)

# k1.2 — What Differs Across Distros (and Why It Matters) 🔎

Even though Linux systems feel similar, the *pain points* usually come from a handful of predictable differences. Learn these once, and you’ll be able to “translate” smoothly between Debian/Ubuntu and RHEL-like systems (Rocky/Alma).

---

### 1) Package management (how you install/update software)

This is the **#1 day-to-day difference**.

- **Debian/Ubuntu:** `apt` (packages are typically `.deb`)
- **RHEL family:** `dnf` (packages are typically `.rpm`)

**Why you care:**
- Commands differ (`apt install` vs `dnf install`).
- Package *names* sometimes differ (e.g., dev headers, utilities, service names).
- Default repo contents and versions can vary a lot (important for PHP/Node).

---

### 2) Release cadence & “stability vs freshness”

Distros make different tradeoffs:

- **Debian stable / RHEL-like:** prioritize **predictability** and long support windows.
- **Ubuntu LTS:** also stable, but often ships **newer** versions than Debian stable.

**Why you care:**
- You might not get the newest PHP/Node from default repos on a “stable” distro.
- You’ll frequently choose between:
  - *distro packages* (stable, integrated), vs
  - *vendor repos / language version managers* (newer, more moving parts)

---

### 3) Security frameworks & defaults (MAC systems)

Two common “why is this blocked?” systems:

- **SELinux** (very common/enforced on RHEL family)
- **AppArmor** (common on Ubuntu)

**Why you care:**
- Your config can look correct, permissions can look correct, and it still fails.
- Troubleshooting often means:  
  **service logs + system logs + security policy** (not just “chmod it”)

---

### 4) Firewall tooling (same concept, different interface)

The *concept* is universal: allow only what you need.

But tooling differs:

- **Ubuntu commonly:** UFW (friendly frontend)
- **RHEL family commonly:** firewalld

**Why you care:**
- Opening ports (like 80/443) is expressed differently.
- Guides online often assume one tool; you’ll learn the underlying idea so you can adapt.

---

### 5) Defaults, layout conventions, and “where is the config?”

Most Linux systems follow similar standards (especially for `/etc`, `/var`, logs), but defaults still vary:

- Different default config paths *per service*
- Different default module layouts (e.g., Nginx includes, PHP-FPM pool configs)
- Different service names in systemd

**Why you care:**
- You’ll learn to *locate* configuration and logs reliably, rather than memorize one distro’s exact path.

---

### A useful “translation mindset” ✅

When moving between distros, ask the same questions every time:

1. **How do I install it here?** (APT vs DNF, package names)
2. **What’s the service name?** (`systemctl status …`)
3. **Where are the config + logs?** (`/etc/...`, `/var/log/...`, `journalctl`)
4. **Is a security framework blocking it?** (SELinux/AppArmor indicators)

---

### Tiny practice prompt (optional)

Tell me which family you want to *start* with in examples later:

1. Debian/Ubuntu  
2. RHEL-like (Rocky/Alma)  
3. Keep everything dual-written (both), whenever it matters

# k1.3 — Your Working Environment (Local vs Server) 🧩

Your goal here is to pick a setup that’s **safe**, **realistic**, and **distro-neutral**—so you can learn fundamentals now and specialize later (e.g., Debian) without re-learning everything.

---

## The 4 common ways you’ll “use Linux”

1. **Local Linux (installed on your own machine)**
   - **Best for:** making Linux your primary daily environment.
   - **Pros:** fastest feedback loop; you live in the terminal; no SSH needed.
   - **Cons:** higher risk of breaking your personal system; more time spent on desktop/hardware quirks (graphics, Wi‑Fi, drivers) vs server skills.

2. **Virtual Machines (VMs) — recommended for learning**
   - **Best for:** learning system administration safely.
   - **Pros:**
     - You can run multiple distros side-by-side (Debian + Ubuntu + Rocky) without “committing.”
     - **Snapshots** give you instant rollback.
     - Closer to real server behavior than containers (full OS, boot process, systemd).
   - **Cons:** uses more RAM/disk; networking can be one extra layer of “why can’t I reach it?” (good learning, sometimes annoying).

3. **Remote Servers (VPS / cloud instances)**
   - **Best for:** practicing the *real* workflow you’ll use in production.
   - **Pros:**
     - Real networking: public IP, DNS, firewalls, TLS certificates.
     - Realistic constraints: limited resources, security posture matters.
   - **Cons:** mistakes can lock you out (SSH/firewall), expose services, or cause downtime.

4. **Containers (Docker/Podman)**
   - **Best for:** reproducible app environments and portability.
   - **Pros:** consistent dev/prod-ish environments; great for Node/React services; easy to reset.
   - **Cons:** not a full “Linux server admin” experience:
     - Containers share the host kernel.
     - systemd/services/logging feel different.
     - Filesystem + networking are *similar*, but with container-specific concepts layered on.

---

## A practical recommendation (distro-neutral, web-dev friendly)

If your aim is “learn Linux fundamentals → later dive into Debian → deploy web apps/WordPress,” this progression works well:

1. **Start with 1 VM as your sandbox server**
   - Treat it like a real server: you “admin it,” run services, read logs, manage users, etc.
   - Use snapshots before changes.

2. **Add a VPS later (optional but valuable)**
   - Once you’re comfortable with SSH, services, and logs, a VPS teaches DNS/TLS/firewall realities quickly.

3. **Add containers when you hit app workflow needs**
   - Especially useful for Node, background workers, local dev parity, and packaging apps cleanly.

---

## What “terminal options” actually mean in practice

Common workable combos:

1. **Local terminal + VM**
   - You open a terminal on your host OS and SSH into the VM (or use the VM console).

2. **Local terminal + VPS**
   - Your daily reality for servers: `ssh user@server`.

3. **VS Code Remote (SSH)**
   - Edit files *on the remote machine* with a local editor UI.
   - Very effective for learning because you still use Linux paths, permissions, and tools—just with nicer editing.

---

## Quick decision guide ✅

- Choose **VM** if you want: *safe break/fix learning* + *full OS experience*.
- Choose **VPS** if you want: *real-world ops practice* + *DNS/TLS/firewall experience* (higher stakes).
- Choose **containers** if you want: *app portability and reproducible environments* (not a replacement for OS fundamentals).
- Choose **local Linux** if you want: *Linux as your daily driver* (more lifestyle shift).

---

### One question to tailor the labs going forward
What are you working on right now: **Windows**, **macOS**, or **Linux**—and are you open to using a **VM** as your primary sandbox?

# k1.4 — Safety & Learning Workflow 🛡️

The goal here is to make you **fast at learning** without “mystery breakage” or data loss. Your two pillars are:

- **Reversibility** (you can undo changes)
- **Traceability** (you can explain what changed and why)

---

### 1) Always have a rollback

1. **Use snapshots for “big steps”**
   - If you’re learning in a VM, take a **snapshot** before:
     - installing a web stack
     - changing firewall rules
     - editing service configs (Nginx/PHP-FPM/SSH)
     - doing major upgrades
   - Name snapshots clearly, e.g. `pre-nginx`, `before-php82`, `working-tls`.

2. **Back up configs before you edit**
   - Use simple, consistent backups:
     - `cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.bak`
     - Or add a timestamp:
       - `cp file file.$(date +%F_%H%M).bak`

3. **Keep “known good” copies**
   - For key files, keep a minimal working baseline you can restore quickly (especially useful for Nginx virtual hosts and PHP-FPM pools).

---

### 2) Make changes intentionally (one variable at a time)

1. **Change one thing → test → observe**
   - After each change, immediately validate:
     - Is the service still running?
     - Did logs change?
     - Is the port listening?
     - Does the browser/curl test pass?

2. **Prefer small edits over big rewrites**
   - Comment or duplicate blocks rather than deleting until you’re confident.

3. **Avoid “random fix” spirals**
   - If you try 5 things at once, you won’t know which one worked (or what caused the break).

---

### 3) Keep a tiny change log (it pays off quickly)

Use a simple text file (e.g. `~/lab-notes.md`) and record:

- **What** you changed (file/service)
- **Why** you changed it
- **How** you tested it
- **What happened** (success/error + log snippet)

Example format:

- `2026-04-04` — edited `/etc/nginx/sites-available/example`
  - Reason: add reverse proxy to app on `:3000`
  - Test: `nginx -t`, `systemctl reload nginx`, `curl -I http://localhost`
  - Result: OK / or error + relevant line from logs

This becomes your personal “ops memory” ✅

---

### 4) Practice in layers (a safe progression)

Follow this order to minimize confusion:

1. **Shell basics**
   - navigation, reading files, pipes/redirection
2. **Files & permissions**
   - ownership, `chmod`, web root safety, troubleshooting 403/permission errors
3. **Services + logs**
   - `systemctl`, `journalctl`, knowing where to look when something fails
4. **Networking + firewall**
   - ports, DNS basics, local vs public reachability
5. **Web stack + TLS**
   - Nginx/Apache, PHP-FPM, DB, Let’s Encrypt renewals

Each layer assumes the previous one—this prevents “I don’t even know what I broke” moments.

---

### 5) A minimal “safe workflow” you can reuse

When making a change to a service (Nginx/PHP/SSH), do this every time:

1. **Backup**
   - Copy the config file you’re touching.
2. **Validate config**
   - Example pattern:
     - Nginx: `nginx -t`
     - (Other services have equivalents; you’ll learn them as we go.)
3. **Reload, don’t restart (when possible)**
   - Reload applies changes with less downtime and less risk.
4. **Check logs immediately**
   - Use service logs to confirm it started cleanly.
5. **Test from the client side**
   - `curl`, browser, or a health endpoint.

---

### Optional: tell me your practice setup

To tailor the labs, which environment will you use first?

1. **VM** (VirtualBox/VMware/Proxmox)
2. **VPS** (a real server over SSH)
3. **WSL/macOS terminal + remote Linux**
4. **Containers only** (Docker)