Linux & Operating Systems Fundamentals: Complete Guide

Master Linux and operating system fundamentals: kernel space, processes, virtual memory, file permissions, shell pipes, systemd, and safe Bash scripting.

N

NeuraQuiz Admin

November 11, 2026 • 21 min read

Linux & Operating Systems Fundamentals: Complete Guide

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

Step 1

OS Architecture & Kernel Basics

Step 2

Processes, Threads & Memory

Step 3

Filesystem & Access Permissions

Step 4

Shell Pipelines & Daily Commands

Step 5

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.

Strictly speaking, Linux is only the kernel—the core program managing hardware, memory, and processes. Distributions like Ubuntu, Debian, Fedora, and Alpine combine the Linux kernel with GNU tools, a package manager, and an init system to form a complete OS.

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.

Operating system architecture diagram showing user applications, system call interface, OS kernel modules, and physical hardware

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.

💡
Watch every system call a program makes in real time with 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.

Memory layout diagram comparing isolated processes with multi-threaded shared memory

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.
FeatureProcessThread
Memory SpaceIsolated virtual address spaceShares heap, code, and globals
Communication (IPC)Pipes, sockets, signals, shared memoryDirect shared memory with locks
Context Switch CostHigher (swaps page tables / TLB)Lower (keeps same address space)
Failure Blast RadiusContained to one processCrashes entire parent process
Creation OverheadHigher (fork() + Copy-on-Write)Lower (clone() in existing process)
Best FitIndependent services, security isolationConcurrent 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 by Ctrl+C to 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 try SIGTERM first.

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.

⚠️
When an application vanishes without logging an error, run 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

DirectoryPurposeTypical ContentsOperational Notes
/Root of the filesystem treeTop-level mount pointNever store personal or app files directly here
/bin & /usr/binUser commands and binariesls, cat, grep, bash, git/bin symlinks to /usr/bin on modern distros
/sbin & /usr/sbinSystem admin binariesiptables, fdisk, mkfsUsed for maintenance and root operations
/etcHost configuration files/etc/fstab, /etc/ssh/sshd_configPlain-text configs; include in backups
/homeUser home directories/home/alex/.bashrc, projectsOne subdirectory per regular user
/varVariable runtime data/var/log, databases, cachesMonitor disk growth closely in production
/usrRead-only userland softwareBinaries, libraries, docsLargest part of the OS install
/tmpTemporary scratch filesBuild artifacts, temp socketsOften cleared on reboot; world-writable
/proc & /sysVirtual kernel filesystems/proc/cpuinfo, /proc/<pid>/statusGenerated in RAM; consumes zero disk space

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.

Visual cheat sheet explaining Linux rwx chmod file permissions and core root directory hierarchy

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.

bash
# 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/api
🚨
Never run chmod 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:

  1. Standard Input (stdin, FD 0): Input stream (normally your keyboard).
  2. Standard Output (stdout, FD 1): Normal output stream (your terminal).
  3. Standard Error (stderr, FD 2): 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 (|):

OperatorStream AffectedBehaviorExample
>stdout (FD 1)Overwrites target filels -la > files.txt
>>stdout (FD 1)Appends output to filedate >> audit.log
2>stderr (FD 2)Sends errors to a filefind /etc -name "*.conf" 2> err.log
&>stdout + stderrCaptures both streams together./build.sh &> build.log
2>&1stderr into stdoutMerges errors into output streammake > build.log 2>&1
<stdin (FD 0)Reads input from a filewc -l < users.csv
|stdout to next stdinChains commands in a pipelineps 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.

bash
# 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/null

8. Twenty Essential Daily Linux Commands

Mastering these 20 core commands covers nearly every daily navigation, debugging, and administration task.

  1. pwd — Prints your current working directory.
  2. ls -lah — Lists files in long format with hidden files (-a) and human-readable sizes (-h).
  3. cd — Changes directories (cd - toggles to the previous folder; cd ~ returns home).
  4. mkdir -p — Creates nested directories safely without failing on existing parents.
  5. cp -r — Copies files or directories recursively.
  6. mv — Moves or renames files and folders.
  7. rm -i / rm -rf — Deletes files permanently without a trash bin; verify paths before using -rf.
  8. find — Locates files by name, size, age, or permissions (find . -name "*.log" -mtime +7).

Viewing and Searching Text

  1. cat — Prints short files or joins multiple files to stdout.
  2. less — Scrolls large files cleanly without loading everything into RAM (/text searches, q quits).
  3. head / tail — Shows the top or bottom lines; tail -f app.log streams live log writes.
  4. grep -rn — Searches files and folders recursively for text or regex matches.

Process, Disk, and Network Diagnostics

  1. ps aux — Snapshots all running processes, PIDs, CPU/RAM usage, and commands.
  2. top / htop — Monitors live CPU load, memory pressure, and active processes.
  3. df -h — Shows free and used disk capacity per mounted filesystem.
  4. du -sh * — Totals disk space consumed by each item in the current directory.
  5. free -h — Displays RAM, available memory, cache, and swap usage.
  6. ss -tulnp — Lists listening TCP/UDP ports and the processes bound to them.
  7. curl -i — Sends HTTP requests and displays headers and status codes.
  8. ssh — Connects securely to remote Linux servers (ssh user@host).
bash
# 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 6

9. 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).

bash
# 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" -f

Package 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:

  1. #!/usr/bin/env bash — Locates bash via PATH for portability across systems.
  2. 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.

bash
#!/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.

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.

Test Your Linux & Operating Systems Knowledge

Interactive Skill Check

Ready to test your Operating Systems knowledge?

Put what you just read into practice with timed scenario questions and instant explanations.