$ grep ' 500 ' access.log | awk '{print $7}' | sort | uniq -c | sort -rn | head

Linux

Linux is an open-source operating system kernel, packaged with tools into distributions such as Ubuntu, Debian, Red Hat Enterprise Linux, Rocky, Amazon Linux and Alpine. It runs nearly every server, cloud VM and container in the world, so it is where your databases, Kafka brokers, Spark executors and Airflow workers actually live. Knowing Linux means you can log into a box, find out why a job is slow or dead, and fix it, usually with a handful of small commands joined by pipes.

Small tools, joined by pipes

Each command does one thing and writes plain text. The pipe | connects the stdout of one command to the stdin of the next. All stages run at the same time and stream line by line, so this works on a 50 GB log without temp files. Below: which endpoints fail most often, from a web server access log where each line looks like 203.0.113.7 - - [17/Oct/2026:18:30:01 +0000] "GET /cart HTTP/1.1" 500 512.

$ grep ' 500 ' access.log | awk '{print $7}' | sort | uniq -c | sort -rn | head -2 > top.txt
A log shrinks into an answer, one stage at a time
access.log 9 lines 200/home 500/cart 500/pay 404/img 500/cart 500/api 200/pay 500/pay 500/cart | stdout → stdin grep ' 500 ' 6 lines 500/cart 500/pay 500/cart 500/api 500/pay 500/cart | awk '{print $7}' 6 lines /cart /pay /cart /api /pay /cart | sort 6 lines /api /cart /cart /cart /pay /pay | uniq -c 3 lines 1 /api 3 /cart 2 /pay | sort -rn 3 lines 3 /cart 2 /pay 1 /api | head -2 2 lines 3 /cart 2 /pay > top.txt file stdout (fd 1) → top.txt, overwritten on every run stderr (fd 2) never enters the pipe: it still hits the screen
  1. The raw log: one line per request. We want the endpoints that return HTTP 500 most often.
  2. grep ' 500 ' keeps only matching lines. Its stdout becomes the next command's stdin.
  3. awk '{print $7}' splits each line on spaces and keeps field 7, the request path.
  4. sort puts equal lines next to each other, so uniq -c can collapse them into counts. uniq only merges adjacent duplicates.
  5. sort -rn ranks by the number, biggest first, and head -2 keeps the top two.
  6. > top.txt sends the final stdout to a file. Error messages travel on stderr, which skips both the pipe and the file unless you redirect it with 2>.

Every process starts with three open file descriptors. Redirection rewires them:

Syntax Meaning
cmd > out.txt stdout (fd 1) to a file, overwriting it
cmd >> out.txt stdout appended to the end of the file
cmd 2> err.txt stderr (fd 2) to a file
cmd > all.log 2>&1 stdout to the file, then stderr to wherever stdout points (order matters)
cmd > /dev/null 2>&1 discard everything
cmd < in.txt stdin (fd 0) from a file
cmd1 | cmd2 stdout of cmd1 into stdin of cmd2
cmd | tee out.txt write to a file and keep passing it down the pipe

By default, a pipeline’s exit status is the status of its last command, so grep ... missing.log | sort “succeeds” even when grep failed. set -o pipefail fixes that (see shell scripts).

The ideas that matter

  • A kernel, not a whole OS. The kernel shares CPU, memory, disks and the network between programs. A distribution adds the shell, tools and a package manager (apt, dnf, apk).
  • Everything is a file. Regular files, directories, devices (/dev/sda), sockets and pipes are all opened, read and written the same way, through file descriptors.
  • Processes. Every running program is a process with a PID, a parent, an owner, environment variables and open file descriptors. A process exits with a status code: 0 is success, anything else is failure. Schedulers like Airflow decide task success from that code.
  • Users and permissions. Each file has an owner, a group and rwx bits for owner, group and others. root bypasses checks, which is why services should run as their own unprivileged user.
  • The kernel isolates. Namespaces give a process its own view of PIDs, network and mounts; cgroups cap its CPU and memory. Together they are what a container is.

Directory structure

There are no drive letters. Everything hangs off one tree that starts at /, and extra disks are mounted somewhere inside it (/mnt/data, /var/lib/postgresql).

Path Holds
/ The root of the tree
/home/<user> (~), /root User home directories; ~ is a shortcut for yours
/etc System and service configuration as plain text (/etc/hosts, /etc/postgresql/, /etc/os-release)
/var/log, /var/lib Data that changes: logs, and service data (/var/lib/docker)
/tmp Scratch space for anyone, often wiped on reboot
/usr/bin, /usr/local/bin, /opt Installed programs; /usr/local and /opt for software outside the package manager
/dev Devices as files: disks, terminals, and /dev/null, which swallows anything written to it
/proc, /sys Live kernel and process information, generated on the fly (/proc/meminfo, /proc/<pid>/limits)

Paths starting with / are absolute; anything else is relative to where you are. . is the current folder, .. the parent.

Anatomy of a command

alice@etl-01:~$  ls      -la       /var/log
└── prompt ───┘  command options   argument
user@host:folder         (flags)

The terminal is the window; the shell (bash, zsh) is the program inside it that parses the line, expands ~, * and $VAR, and starts the command. Short options can be combined (-l -a = -la); long options are spelled out (--all). Quote arguments that contain spaces or *: grep "connection reset" app.log.

Commands you will use every week

Task Commands
Move around pwd, ls -lah, cd dir, cd .., cd - (back to the previous folder)
Manage files mkdir -p a/b/c, touch, cp -r, mv (move or rename), rm -r (no trash can)
Read files cat, less (/ to search, q to quit), head -n 5, tail -n 20, tail -f app.log
Search grep -rn "TODO" ., grep -i / -v / -c, find . -name '*.parquet'
Transform text sed, awk, cut, sort, uniq -c, wc -l, jq for JSON
Disk df -h (free space per filesystem), du -sh * (what is using it)
Processes and load ps aux, top / htop, kill, pgrep -a, uptime
Memory free -h, dmesg -T | grep -i oom
Network ss -tlnp (who listens on which port), curl -v, dig, nc -vz host port
Services and logs systemctl status airflow-scheduler, journalctl -u kafka -f
Remote work ssh, scp, rsync -avz, tmux (keep a session alive after you disconnect)

sed and awk one-liners

sed edits streams of text; awk treats each line as columns ($1, $2, … split on whitespace, or on -F).

sed 's/http:/https:/g' urls.txt         # replace every match, print the result
sed -i 's/8080/9090/' app.conf          # edit the file in place (GNU sed; macOS needs -i '')
sed -n '10,20p' big.log                 # print only lines 10 to 20

awk '{print $1}' access.log             # first column: client IPs
awk -F: '{print $1}' /etc/passwd        # split on ':' and list every username
awk '$9 == 404' access.log              # only rows whose 9th field is 404
awk -F, '{s += $3} END {print s}' sales.csv   # sum a CSV column (no quoted commas)

For real CSV with quoted fields, reach for csvkit, duckdb or Python instead of awk -F,.

History and shortcuts

Key or command Does
Tab (twice) Complete commands and paths (show all options)
↑ / ↓ Previous / next command
Ctrl-R Search history as you type; press again for older matches
Ctrl-A / Ctrl-E Jump to start / end of the line
Ctrl-C Stop the running command (not copy)
Ctrl-L Clear the screen
history, !42 Numbered list of past commands; rerun number 42
!! The previous command: sudo !! reruns it as root

Getting help and installing software

man ls                 # the full manual; q quits, / searches
ls --help              # short summary
tldr tar               # community examples (install tldr first)
type cd                # builtin, alias or file?
which python3          # which file runs when you type python3

sudo apt update                 # refresh the package list (Debian, Ubuntu)
apt search htop
sudo apt install htop
sudo apt remove htop

Red Hat family distributions use dnf install, Alpine (common in container images) uses apk add. sudo runs one command as root: read the whole line before you press Enter.

File permissions

$ ls -l etl.sh
Reading a permission string, then changing it
$ ls -l etl.sh - rwx r-x --- alice data etl.sh type- file owner · ualice group · gdata others · oeveryone else 4+2+14+0+10+0+0 750 r=4 · w=2 · x=1 octal 750 readwriterun owner yesyesyes group members yesnoyes everyone else nonono Permission denied r 4+0+0 4 octal 754 yes read only $ chmod 754 etl.sh # same as: chmod o+r etl.sh sam etl sam etl $ sudo chown sam:etl etl.sh # new owner and group, same bits
  1. ls -l shows a 10-character mode, then the file's owner (alice), its group (data) and its name.
  2. Character 1 is the type (- file, d directory, l symlink). Then three rwx triplets: owner, group, others.
  3. Each triplet is a sum: r=4, w=2, x=1. rwx = 7, r-x = 5, --- = 0, so the mode is 750.
  4. The owner can read, edit and run the script; members of the group can read and run it; everyone else gets Permission denied.
  5. chmod changes the bits. 754 adds read for others: they can now see the script but still not run it.
  6. chown changes who the triplets apply to. The bits stay the same, but now sam is the owner and group etl gets r-x. Only root may give a file away.
Command Effect
chmod +x deploy.sh Make a script runnable: ./deploy.sh
chmod 600 secrets.env rw-------: only the owner can read it. SSH refuses private keys that are more open
chmod 755 dir Typical for directories: everyone can enter and list, only the owner can write
chmod u+x,g-w,o-r file Symbolic form: add or remove bits per class
sudo chown sam:etl report.csv New owner and group
id, groups Which user and groups you are

On a directory, r lets you list names, w lets you create and delete files inside it, and x lets you enter it (cd) and reach files by path.

A symbolic link is a tiny file that holds a path to another file or folder. A filename itself is only a pointer to an inode, the record that holds the data location and metadata; a hard link is a second name for the same inode.

ln -s releases/v2.3 current        # current -> releases/v2.3
ls -l current                      # lrwxrwxrwx ... current -> releases/v2.3
ln -sfn releases/v2.4 current      # repoint it: an instant "deploy"
readlink current                   # releases/v2.4
ln data.csv data-backup.csv        # hard link: two names, one inode (ls -i shows the number)
Symbolic link Hard link
Points to A path The inode itself
Target deleted Link breaks (“dangling”) Data survives until the last name is removed
Directories, other filesystems Yes No
Typical use current -> releases/v2.4, config switching Rare; backups and deduplication tools

Processes and signals

ps aux                      # snapshot of every process: user, PID, CPU, memory, command
ps aux | grep airflow       # or: pgrep -a airflow
top                         # live view (htop is nicer); q quits
kill 1234                   # send SIGTERM: please stop
kill -9 1234                # send SIGKILL: stop now, last resort
sudo ss -tlnp | grep 8080   # which process is listening on port 8080?

A signal is a small message the kernel delivers to a process.

Signal Number Sent by Can the process handle it?
SIGINT 2 Ctrl-C Yes
SIGTERM 15 kill, systemd, Kubernetes on shutdown Yes: flush, checkpoint, close connections, exit
SIGKILL 9 kill -9, the OOM killer No: the process vanishes mid-write
SIGHUP 1 Terminal closed; many daemons reload config on it Yes

Orchestrators send SIGTERM, wait a grace period, then SIGKILL, so long-running jobs should catch SIGTERM and stop cleanly. A process killed by a signal exits with 128 + signal number: 137 means SIGKILL, 143 means SIGTERM.

Environment variables

Every process has an environment: a list of NAME=value strings it inherits from its parent. A plain shell variable stays in the current shell; export puts it into the environment so every child process gets a copy.

NAME=alice
bash -c 'echo $NAME'      # empty line: the child cannot see it
export NAME
bash -c 'echo $NAME'      # alice
export PORT=8080          # set and export in one go
PORT=9090 python app.py   # set only for this one command
echo $PATH                # /usr/local/bin:/usr/bin:/bin
  • Inheritance flows one way. A child gets a copy; changes it makes never reach the parent. That is why a script cannot change your shell’s directory or variables unless you source it.
  • PATH is the list of folders searched for commands, left to right. “command not found” means the program is not in any of them; which shows which one wins.
  • ~/.bashrc (or ~/.zshrc) runs in every new interactive shell: keep exports and aliases there and reload with source ~/.bashrc.
  • Configuration and secrets such as DATABASE_URL are passed to apps as environment variables instead of being hard-coded. Locally they often live in a .env file, loaded by your tool or with set -a; source .env; set +a. Keep .env out of Git.

Shell scripts

A script is commands saved in a file. This one backs up a folder:

#!/usr/bin/env bash
set -euo pipefail                 # stop on errors, unset variables and failed pipes

SRC="${1:-$HOME/workshop}"        # first argument, with a default
DEST="$HOME/backups"
STAMP=$(date +%F_%H%M)            # command substitution: 2026-10-17_1830

mkdir -p "$DEST"
tar -czf "$DEST/$STAMP.tar.gz" "$SRC"
echo "Backup saved: $STAMP"
chmod +x backup.sh
./backup.sh ~/workshop/notes
echo $?                           # exit code of the last command: 0 = success
Piece Why
#!/usr/bin/env bash The shebang: which interpreter runs the file, found through PATH
set -e Exit at the first failing command instead of carrying on with half the data
set -u Using an unset variable is an error, not an empty string (no accidental rm -rf "$DIR/")
set -o pipefail A pipeline fails if any stage fails, not only the last
$1, $2, $@, $# Arguments, all arguments, how many
"$VAR" Always quote variables so spaces in file names do not split them
exit 1 Report failure to whatever called the script: cron, Airflow, CI

Run shellcheck on every script; it catches most quoting and logic bugs. Once a script grows past a page or needs real data structures, rewrite it in Python.

Where data jobs meet the kernel

  • The OOM killer. When memory runs out, or a container hits its cgroup limit, the kernel kills a process. Your Spark executor or pod just vanishes with exit code 137 (128 + SIGKILL). Check dmesg or kubectl describe pod, then raise the limit or reduce memory use.
  • File descriptor limits. Kafka, Elasticsearch and databases keep many files and sockets open. The default ulimit -n of 1024 is far too low; services set LimitNOFILE in their systemd unit.
  • The page cache. Linux uses free RAM to cache disk reads. “Free” memory near zero is normal; look at available in free -h.
  • Cron and systemd timers. The original schedulers. Still fine for a single box; use a real orchestrator once jobs depend on each other.

Practice

Try these in a terminal (a Linux VM, WSL, or a Docker container: docker run -it ubuntu bash):

  1. Create ~/workshop/logs and ~/workshop/notes with one command. Hint: mkdir -p and {a,b}.
  2. Which distribution and version are you running? Hint: /etc/os-release.
  3. How many user accounts exist on the machine? Hint: /etc/passwd, wc -l.
  4. List every .conf file directly inside /etc. Hint: find -maxdepth 1 -name.
  5. Save the listing of /etc into ~/workshop/notes/etc.txt. Hint: >.
  6. From that file, show only the names containing “net”. Hint: grep.
  7. Find your five most-used commands. Hint: history | awk '{print $2}' | sort | uniq -c | sort -rn | head -5.
  8. Bonus: the five biggest items in /var/log. Hint: du -ah, sort -rh.

Common mistakes

  • Running everything as root, including containers. One bug becomes a full compromise.
  • Filling the disk with logs. Configure log rotation (logrotate, journald limits) before it happens at 3 a.m.
  • chmod 777 to fix a permission error. Find the right owner and group instead.
  • > when you meant >>. One character truncates the file you were trying to append to.
  • kill -9 first. SIGKILL skips cleanup, leaving lock files, half-written output and uncommitted offsets. Send SIGTERM and wait.
  • Editing config on one server by hand. It drifts and can’t be rebuilt. Use Infrastructure as Code or at least a container image.
  • Ignoring exit codes in shell scripts. Start scripts with set -euo pipefail so a failed step stops the job instead of loading half the data.

Learning Resources

Books

Courses and practice

Reference

See also: SSH, Networking, Git.