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.
- The raw log: one line per request. We want the endpoints that return HTTP 500 most often.
grep ' 500 'keeps only matching lines. Its stdout becomes the next command's stdin.awk '{print $7}'splits each line on spaces and keeps field 7, the request path.sortputs equal lines next to each other, souniq -ccan collapse them into counts.uniqonly merges adjacent duplicates.sort -rnranks by the number, biggest first, andhead -2keeps the top two.> top.txtsends the final stdout to a file. Error messages travel on stderr, which skips both the pipe and the file unless you redirect it with2>.
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
rwxbits for owner, group and others.rootbypasses 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 htopRed 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 -lshows a 10-character mode, then the file's owner (alice), its group (data) and its name.- Character 1 is the type (
-file,ddirectory,lsymlink). Then three rwx triplets: owner, group, others. - Each triplet is a sum: r=4, w=2, x=1.
rwx= 7,r-x= 5,---= 0, so the mode is 750. - The owner can read, edit and run the script; members of the group can read and run it; everyone else gets Permission denied.
chmodchanges the bits.754adds read for others: they can now see the script but still not run it.chownchanges 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.
Symbolic and hard links
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
sourceit. PATHis the list of folders searched for commands, left to right. “command not found” means the program is not in any of them;whichshows which one wins.~/.bashrc(or~/.zshrc) runs in every new interactive shell: keep exports and aliases there and reload withsource ~/.bashrc.- Configuration and secrets such as
DATABASE_URLare passed to apps as environment variables instead of being hard-coded. Locally they often live in a.envfile, loaded by your tool or withset -a; source .env; set +a. Keep.envout 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
dmesgorkubectl 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 -nof 1024 is far too low; services setLimitNOFILEin their systemd unit. - The page cache. Linux uses free RAM to cache disk reads. “Free” memory near zero is normal; look at
availableinfree -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):
- Create
~/workshop/logsand~/workshop/noteswith one command. Hint:mkdir -pand{a,b}. - Which distribution and version are you running? Hint:
/etc/os-release. - How many user accounts exist on the machine? Hint:
/etc/passwd,wc -l. - List every
.conffile directly inside/etc. Hint:find -maxdepth 1 -name. - Save the listing of
/etcinto~/workshop/notes/etc.txt. Hint:>. - From that file, show only the names containing “net”. Hint:
grep. - Find your five most-used commands. Hint:
history | awk '{print $2}' | sort | uniq -c | sort -rn | head -5. - 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 777to 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 -9first. 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 pipefailso a failed step stops the job instead of loading half the data.
Learning Resources
Books
- How Linux Works, 3rd edition: Brian Ward
- The Linux Command Line, 2nd edition: William Shotts, free PDF
- Linux Pocket Guide, 4th edition: Daniel J. Barrett
- Systems Performance, 2nd edition: Brendan Gregg, for when you need to know why it’s slow
Courses and practice
- The Missing Semester of Your CS Education: MIT, shell, scripting and tools
- Introduction to Linux: Full Course for Beginners: freeCodeCamp
- OverTheWire: Bandit: learn the shell through a game
- Linux Journey
Reference
- Linux man pages online
- GNU Bash manual
- ShellCheck: finds bugs in shell scripts
- Linux Performance: Brendan Gregg’s tools and checklists
See also: SSH, Networking, Git.