Every time you run a Python script, launch a container, or deploy a web service, an operating system does the heavy lifting underneath. It turns raw silicon—CPU cores, RAM sticks, NVMe drives, and network cards—into a predictable environment where dozens of programs run side by side without interfering with one another.
Most developers learn just enough Linux to copy commands and hope nothing breaks. That works until a production server runs out of memory, a service refuses to bind to port 8080, or a script deletes the wrong folder.
This guide gives you a clear mental model of how Linux and modern operating systems work, paired with the daily command-line habits senior engineers rely on. If you are building your broader coding foundation, pair this guide with Programming Fundamentals.
Your Linux & Operating Systems Learning Roadmap
OS Architecture & Kernel Basics
Processes, Threads & Memory
Filesystem & Access Permissions
Shell Pipelines & Daily Commands
Systemd Services & Bash Scripts
1. What an Operating System Actually Does
Without an operating system (OS), every application would need custom code to talk directly to specific motherboard chipsets, SSD controllers, and network adapters. Two programs running together would overwrite each other's memory and fight over CPU cores.
An operating system acts as a trusted referee between software and physical hardware through three core responsibilities.
Hardware Abstraction
Hardware varies across CPU architectures, SSD vendors, and network cards. The OS hides those differences behind consistent software interfaces.
Applications never send raw electrical commands to flash storage. Instead, they ask the OS to open a file path, read bytes, and write bytes, while device drivers translate those requests into hardware instructions.
Resource Management
A typical server runs hundreds of tasks concurrently, even with only a few physical CPU cores. The OS slices CPU time, divides RAM, and schedules disk and network I/O so runnable programs share hardware fairly.
When one process pauses for a slow network response, the OS immediately hands the CPU core to another waiting task.
Isolation and Protection
Buggy or untrusted programs must not crash the entire machine or read another user's private data. The OS enforces strict boundaries around memory, files, and device access.
If your C program dereferences a null pointer, the OS terminates that single process with a segmentation fault instead of crashing the kernel. That isolation—extended by Linux namespaces and cgroups to isolate process trees and cap CPU or RAM—makes multi-user servers, virtual machines, and containers possible.
2. User Space, Kernel Space, and System Calls
Modern CPUs enforce hardware privilege levels—often called protection rings—to separate trusted OS code from applications. Linux divides execution into kernel space and user space.

User Space vs. Kernel Space
Kernel space runs with full CPU privileges (Ring 0 on x86-64). Code here can access any memory address, configure hardware registers, schedule tasks, and control storage and network devices.
User space runs in restricted mode (Ring 3 on x86-64). Your browser, terminal shell, Python interpreter, and database server all live in user space and cannot touch physical hardware or another process's memory directly.
The System Call Interface
When a user-space program needs privileged work—like opening a file, allocating memory, or opening a TCP socket—it invokes a system call (syscall). Core Linux syscalls include openat(), read(), write(), fork(), execve(), and socket().
Programs normally call C library wrappers (glibc or musl) rather than raw assembly. The wrapper loads arguments into CPU registers and triggers a trap instruction (syscall on x86-64).
The CPU switches to kernel mode, validates permissions, executes the operation, and returns to user space. Crossing that boundary takes hundreds of nanoseconds, which adds up quickly if code runs millions of tiny unbuffered reads or writes.
strace. Running strace -e trace=openat,read ls /tmp reveals the exact files ls opens and exposes missing configs or permission errors immediately.3. Processes, Threads, and CPU Scheduling
Once you understand the user-kernel boundary, the next step is how the OS runs programs. In Linux, a process is the unit of isolation, while a thread is the unit of execution inside a process.

Processes and Context Switching
A process is a running instance of a program. The kernel tracks it via a Process Control Block (task_struct in Linux) holding its PID, open file descriptors, credentials, and memory mappings.
Because processes do not share memory by default, switching from Process A to Process B requires a context switch: the kernel saves CPU registers, swaps virtual memory page tables, and restores Process B's state.
Threads, IPC, and Shared Memory
A thread runs inside a process and shares heap memory, global variables, and open file descriptors with sibling threads. Each thread maintains only its own CPU registers and call stack.
Thread context switches skip swapping memory mappings, making them faster than process switches. However, shared memory requires locks or atomics to prevent race conditions, and an unhandled crash in one thread kills the whole process.
Because separate processes live in isolated address spaces, they must use Inter-Process Communication (IPC) to coordinate:
- Pipes and Unix Domain Sockets: Kernel-managed byte streams that copy data safely between processes without exposing memory addresses.
- Shared Memory (
shm_open/mmap): Maps the same physical RAM pages into two processes simultaneously. Shared memory delivers maximum throughput for high-frequency data, though both processes must synchronize writes using semaphores or locks.
| Feature | Process | Thread |
|---|---|---|
| Memory Space | Isolated virtual address space | Shares heap, code, and globals |
| Communication (IPC) | Pipes, sockets, signals, shared memory | Direct shared memory with locks |
| Context Switch Cost | Higher (swaps page tables / TLB) | Lower (keeps same address space) |
| Failure Blast Radius | Contained to one process | Crashes entire parent process |
| Creation Overhead | Higher (fork() + Copy-on-Write) | Lower (clone() in existing process) |
| Best Fit | Independent services, security isolation | Concurrent workers, parallel tasks |
CPU Scheduling, Signals, and Zombies
Linux uses a preemptive scheduler (CFS, and EEVDF in newer kernels) so no single CPU-bound task starves other workloads. Each runnable task receives CPU slices weighted by its nice priority (ranging from -20 for highest priority to 19 for lowest priority; use renice to adjust running processes).
Linux controls running processes with asynchronous signals:
SIGINT(2): Sent byCtrl+Cto interrupt a foreground program.SIGHUP(1): Traditionally signals a terminal hangup; modern daemons use it to reload configuration files without restarting.SIGTERM(15): Requests a graceful shutdown so the app can flush buffers and close connections.SIGKILL(9): Terminates a process immediately in the kernel with zero cleanup. Always trySIGTERMfirst.
When a child process exits, its PID stays in the process table until the parent reads its exit status via wait(). If the parent ignores it, the child becomes a zombie process (Z state in ps), holding a PID slot without using RAM until the parent reads the status or exits.
4. Memory Management: RAM, Virtual Memory, and Paging
Applications expect memory to look like one contiguous strip of bytes. Physical RAM, meanwhile, is shared across dozens of processes and kernel caches. Virtual memory bridges that divide.
Virtual Address Spaces and Paging
Every process gets an isolated virtual address space. A pointer like 0x7ffd1000 is a virtual address, never a direct physical RAM stick location.
The CPU's Memory Management Unit (MMU) translates virtual addresses into physical frames in pages (typically 4 KB on x86-64) using kernel page tables, cached in hardware inside the Translation Lookaside Buffer (TLB).
Virtual memory provides three major advantages:
- Isolation: Process A cannot address Process B's physical RAM unless shared pages are explicitly mapped.
- Lazy Allocation: Calling
malloc()reserves virtual pages first; Linux maps physical RAM only when code writes to a page, triggering a minor page fault (no disk read required). - Copy-on-Write (
fork()): Parent and child share read-only physical pages until one writes to a page, keeping process creation fast.
Page Cache, Swap, and the OOM Killer
New Linux users often worry when free -h shows almost zero "free" RAM. Unused RAM is wasted RAM, so Linux uses spare memory as a page cache for disk blocks and reclaims it instantly when apps need memory.
When physical RAM runs low, the kernel pushes inactive memory pages out to swap space on disk. Reading a swapped-out page back into RAM triggers a slow major page fault. If the system spends more time swapping pages back and forth than running application code—a condition called thrashing—latency spikes dramatically.
When both physical RAM and swap run out, Linux triggers the Out-Of-Memory (OOM) killer. The kernel ranks processes by oom_score and terminates the highest-scoring offender to keep the OS alive.
dmesg -T | grep -i oom or journalctl -k. The kernel OOM killer records every process it terminates there.5. The Linux Filesystem Hierarchy Standard (FHS)
Instead of drive letters like C:\, Linux mounts every disk and virtual filesystem into one unified tree rooted at /. The Filesystem Hierarchy Standard (FHS) standardizes where files live across distributions.
Core Directories You Must Know
| Directory | Purpose | Typical Contents | Operational Notes |
|---|---|---|---|
/ | Root of the filesystem tree | Top-level mount point | Never store personal or app files directly here |
/bin & /usr/bin | User commands and binaries | ls, cat, grep, bash, git | /bin symlinks to /usr/bin on modern distros |
/sbin & /usr/sbin | System admin binaries | iptables, fdisk, mkfs | Used for maintenance and root operations |
/etc | Host configuration files | /etc/fstab, /etc/ssh/sshd_config | Plain-text configs; include in backups |
/home | User home directories | /home/alex/.bashrc, projects | One subdirectory per regular user |
/var | Variable runtime data | /var/log, databases, caches | Monitor disk growth closely in production |
/usr | Read-only userland software | Binaries, libraries, docs | Largest part of the OS install |
/tmp | Temporary scratch files | Build artifacts, temp sockets | Often cleared on reboot; world-writable |
/proc & /sys | Virtual kernel filesystems | /proc/cpuinfo, /proc/<pid>/status | Generated in RAM; consumes zero disk space |
Inodes, Hard Links, and Symbolic Links
Linux directories simply map filenames to inode numbers. An inode stores metadata—size, owner UID, group GID, permissions, timestamps, and disk block pointers—everything except the filename itself (stat filename displays it).
- Hard Link (
ln target linkname): Adds another filename pointing to the same inode. Data survives until the last hard link is deleted. Cannot span filesystems or directories. - Symbolic Link (
ln -s target linkname): Creates a shortcut file storing a path string to another target. Deleting the target leaves a broken symlink.
6. Users, Groups, and File Permissions
Linux was built as a multi-user OS, so every file and process belongs to a user and group. Clean permissions prevent accidental outages and limit security exposure.

Reading rwx and Octal Modes
Running ls -l shows a 10-character mode string like -rwxr-xr--. Character one marks file type (- file, d directory, l symlink), followed by three triads: User (owner), Group, and Others.
Each bit has a numeric value: Read (r) = 4, Write (w) = 2, Execute (x) = 1. On directories, r lists filenames, w creates or deletes entries, and x allows cd traversal.
Sum each triad for octal permissions:
chmod 755 script.sh(rwxr-xr-x): Owner reads, writes, and executes (7); group and others read and execute (5). Standard for scripts and directories.chmod 754 deploy.sh(rwxr-xr--): Owner has full control (7), group reads and executes (5), others only read (4).chmod 640 secrets.env(rw-r-----): Owner reads and writes (6), group reads (4), others have no access (0).
Ownership, umask, and Least Privilege
User accounts live in /etc/passwd and /etc/group, while password hashes stay restricted in /etc/shadow. The superuser root (UID 0) bypasses normal file checks.
Default permissions on newly created files are controlled by umask (typically 0022). The shell subtracts the umask from 666 for files (producing 644, rw-r--r--) and from 777 for directories (producing 755, rwxr-xr-x) so new files are never world-writable by accident.
Follow the principle of least privilege: work as a regular user and invoke sudo only for administrative commands, which creates an audit trail in /var/log/auth.log or journalctl and prevents sweeping mistakes.
# Inspect current permissions and ownership
ls -l deploy.sh
# Set owner rwx (7), group r-x (5), others r-- (4)
chmod 754 deploy.sh
# Lock down a private SSH key to owner read/write only
chmod 600 ~/.ssh/id_ed25519
# Change owner to 'appuser' and group to 'www-data'
sudo chown appuser:www-data /var/www/app/config.yaml
# Recursively assign group ownership on a shared directory
sudo chown -R :developers /srv/projects/apichmod 777 on a production folder or script to silence a permission error. World-writable permissions let any local service account tamper with your code or drop malicious binaries.7. The Shell, Pipes, and I/O Redirection
A shell—typically Bash or Zsh—interprets commands, expands variables, launches child processes, and connects their input and output streams.
Standard Streams and File Descriptors
Every Linux process opens three standard file descriptors at startup:
- Standard Input (
stdin, FD0): Input stream (normally your keyboard). - Standard Output (
stdout, FD1): Normal output stream (your terminal). - Standard Error (
stderr, FD2): Error and diagnostic stream, kept separate so errors do not corrupt piped output.
Redirection and Composable Pipelines
Unix tools pass plain text between programs using redirection operators and pipes (|):
| Operator | Stream Affected | Behavior | Example |
|---|---|---|---|
> | stdout (FD 1) | Overwrites target file | ls -la > files.txt |
>> | stdout (FD 1) | Appends output to file | date >> audit.log |
2> | stderr (FD 2) | Sends errors to a file | find /etc -name "*.conf" 2> err.log |
&> | stdout + stderr | Captures both streams together | ./build.sh &> build.log |
2>&1 | stderr into stdout | Merges errors into output stream | make > build.log 2>&1 |
< | stdin (FD 0) | Reads input from a file | wc -l < users.csv |
| | stdout to next stdin | Chains commands in a pipeline | ps aux | grep nginx |
Pairing pipes with grep (pattern matching), awk (column extraction), sort, and uniq lets you inspect massive logs in seconds. Every command also returns a numeric exit status ($?) when it finishes: 0 means success, while 1 through 255 signals an error. Using && runs the next command only if the previous command returned 0, whereas ; runs commands unconditionally.
# Find the top 5 IP addresses triggering HTTP 500 errors
cd /var/log/nginx && \
grep " 500 " access.log | \
awk '{print $1}' | \
sort | \
uniq -c | \
sort -nr | \
head -n 5
# Search YAML configs while hiding permission-denied stderr messages
grep -rn "timeout:" /etc/app/ 2>/dev/null8. Twenty Essential Daily Linux Commands
Mastering these 20 core commands covers nearly every daily navigation, debugging, and administration task.
Navigation and File Management
pwd— Prints your current working directory.ls -lah— Lists files in long format with hidden files (-a) and human-readable sizes (-h).cd— Changes directories (cd -toggles to the previous folder;cd ~returns home).mkdir -p— Creates nested directories safely without failing on existing parents.cp -r— Copies files or directories recursively.mv— Moves or renames files and folders.rm -i/rm -rf— Deletes files permanently without a trash bin; verify paths before using-rf.find— Locates files by name, size, age, or permissions (find . -name "*.log" -mtime +7).
Viewing and Searching Text
cat— Prints short files or joins multiple files tostdout.less— Scrolls large files cleanly without loading everything into RAM (/textsearches,qquits).head/tail— Shows the top or bottom lines;tail -f app.logstreams live log writes.grep -rn— Searches files and folders recursively for text or regex matches.
Process, Disk, and Network Diagnostics
ps aux— Snapshots all running processes, PIDs, CPU/RAM usage, and commands.top/htop— Monitors live CPU load, memory pressure, and active processes.df -h— Shows free and used disk capacity per mounted filesystem.du -sh *— Totals disk space consumed by each item in the current directory.free -h— Displays RAM, available memory, cache, and swap usage.ss -tulnp— Lists listening TCP/UDP ports and the processes bound to them.curl -i— Sends HTTP requests and displays headers and status codes.ssh— Connects securely to remote Linux servers (ssh user@host).
# Locate log files larger than 100 MB
sudo find /var/log -type f -size +100M -exec ls -lh {} +
# Check filesystem usage and find the largest folders in /var
df -h /var && sudo du -sh /var/* | sort -hr | head -n 5
# Inspect available RAM and top 5 memory-hungry processes
free -h && ps aux --sort=-%mem | head -n 69. Systemd Services, Logs, and Package Management
Major Linux distributions use systemd as PID 1—the first user-space process started at boot. Systemd manages background services, auto-restarts failed daemons, and collects structured logs.
Controlling Services with systemctl
Systemd services are configured as unit files under /etc/systemd/system/ or /lib/systemd/system/. Manage them with systemctl:
sudo systemctl status nginx— Checks active state, PID, memory usage, and recent logs.sudo systemctl start|stop|restart nginx— Controls the service immediately.sudo systemctl reload nginx— Reloads config changes without dropping active connections.sudo systemctl enable --now nginx— Starts the service now and enables automatic boot startup.
Systemd also replaces legacy cron jobs for many administrative tasks using timer units (.timer), which trigger .service units on a schedule while capturing full exit statuses and structured logs automatically.
Troubleshooting Ports and Logs with journalctl
Query systemd's binary journal with journalctl using unit filters (-u), live streaming (-f), or error priorities (-p err).
# 1. Verify which process owns port 8080
sudo ss -tulnp | grep :8080
# 2. Check process tree details
ps -ef | grep myapp
# 3. Inspect systemd unit status
sudo systemctl status myapp.service --no-pager
# 4. Stream logs from the past 15 minutes
sudo journalctl -u myapp.service --since "15 minutes ago" -fPackage Management: apt vs. dnf
Linux package managers install verified software from signed repositories and handle dependencies cleanly:
- Debian / Ubuntu (
apt):sudo apt update,sudo apt install -y ripgrep,sudo apt upgrade. - Fedora / RHEL / Rocky (
dnf):sudo dnf check-update,sudo dnf install -y ripgrep,sudo dnf upgrade.
Combine clean package hygiene with version control from Git and GitHub Basics and infrastructure workflows in DevOps Explained Simply.
10. Writing Safe Bash Automation Scripts
Interactive commands work for exploration, while repeatable tasks—backups, health checks, and deployments—belong in version-controlled Bash scripts. By default, Bash ignores failed commands and expands undefined variables to empty strings, which can cause silent data loss.
Defensive Bash Guardrails
Always start scripts with two protective lines:
#!/usr/bin/env bash— LocatesbashviaPATHfor portability across systems.set -euo pipefail— Enables strict mode:-e: Exit immediately when any command fails.-u: Fail on unset variables instead of expanding to"".-o pipefail: Propagate failures from any stage inside a pipe.
Double-quote variables ("$backup_dir") to prevent spaces from splitting arguments, and organize steps into small functions.
#!/usr/bin/env bash
set -euo pipefail
readonly BACKUP_DIR="/var/backups/app"
readonly SOURCE_DIR="/etc/nginx"
readonly SERVICES=("nginx" "postgresql")
readonly TIMESTAMP="$(date +%Y%m%d-%H%M%S)"
log_info() {
printf '[INFO] %s - %s\n' "$(date +%H:%M:%S)" "$1"
}
check_services() {
for svc in "${SERVICES[@]}"; do
if systemctl is-active --quiet "$svc"; then
log_info "Service '$svc' is healthy."
else
printf '[ERROR] Service "%s" is NOT running!\n' "$svc" >&2
return 1
fi
done
}
create_backup() {
mkdir -p "$BACKUP_DIR"
local archive_path="${BACKUP_DIR}/nginx-${TIMESTAMP}.tar.gz"
tar -czf "$archive_path" -C "$(dirname "$SOURCE_DIR")" "$(basename "$SOURCE_DIR")"
log_info "Created backup archive at ${archive_path}"
}
main() {
check_services
create_backup
log_info "Daily health check and backup completed."
}
main "$@"Make the script executable with chmod 750 health_backup.sh and run sudo ./health_backup.sh. Errors route cleanly to stderr, variables stay quoted, and a failed service check stops execution before archiving.
Before deploying any new automation script to a server, run it through shellcheck (shellcheck health_backup.sh). It catches unquoted variables, broken conditionals, and subtle Bash portability bugs before they cause production damage.
Frequently Asked Questions (FAQs)
1. Is Linux an operating system or just a kernel?
Technically, Linux is the kernel managing CPU scheduling, memory, drivers, and filesystems. A "Linux OS" usually refers to a distribution like Ubuntu, Debian, or Fedora that bundles the kernel with GNU tools, libraries, systemd, and a package manager.
2. Why are system calls slower than normal function calls?
A normal function call stays in user space and jumps directly to another code address. A system call forces the CPU to switch privilege rings into kernel mode, validate inputs, execute kernel logic, and return, adding extra CPU cycles per crossing.
3. What is the difference between a zombie process and an orphan process?
A zombie process has exited but remains in the process table until its parent calls wait() to read its exit code. An orphan process is still running after its parent dies; the kernel re-parents it to PID 1 (systemd), which reaps it upon exit.
4. Why does free -h show very little free RAM on a healthy server?
Linux uses spare RAM as a page cache for disk reads so programs run faster. Check the available column in free -h, not free—available memory includes reclaimable cache that the kernel hands back to apps immediately when needed.
5. What is the difference between a hard link and a symbolic link?
A hard link maps a second filename directly to the same inode, so deleting the original name preserves the file data. A symbolic link (ln -s) is a shortcut pointing to a path string and breaks if the target moves or is deleted.
6. Why should I avoid chmod 777 even on test servers?
Setting 777 grants read, write, and execute rights to every local user and service account. It masks real ownership issues in testing and creates critical security holes if repeated in production, where 755 or 640 belongs.
7. Why does > sometimes miss error messages in log files?
The > operator redirects only stdout (FD 1), while errors go to stderr (FD 2). Use command > out.log 2>&1 or command &> out.log to capture both streams in one file.
8. When should I use SIGTERM instead of SIGKILL?
Always send SIGTERM (kill <pid>) first so the process can flush buffers, close sockets, and finish transactions cleanly. Reserve SIGKILL (kill -9 <pid>) for unresponsive processes that ignore SIGTERM.
9. What does set -euo pipefail prevent in Bash scripts?
It prevents silent cascading bugs. Without it, Bash ignores failed commands (-e), expands typos in variable names to empty strings (-u)—turning rm -rf "$DIR/" into rm -rf /—and hides failures in earlier stages of a pipeline (-o pipefail).
Conclusion
Understanding Linux and operating systems transforms how you build, debug, and operate software. Instead of treating servers as black boxes, you can trace user-to-kernel crossings, read memory and process tables accurately, enforce least-privilege permissions, and write safe Bash automation.
Practice these workflows on a local VM, WSL2, or container, and explore deeper systems guides in our Operating Systems category.
