Objectives and prerequisites
By the end of this course, you will be able to find your way around a Linux system, read the state of processes, permissions, storage and services, then diagnose a common failure with reproducible commands. The common thread is a server hosting a small catalogue that breaks down.
Prerequisites: comfortable with a terminal and able to edit a text file. The examples assume a Debian/Ubuntu-like Linux distribution with Bash and systemd, inside a virtual machine or lab container. Do not run destructive commands on a production machine.
Path: chapters 1 to 4 cover the kernel, filesystem, processes and memory; chapters 5 to 8 cover users, storage, the shell and text processing; chapters 9 to 11 cover services, networking and scripts; chapter 12 synthesises diagnosis and operations.
Convention: commands are shown with their expected output or effect. Paths are absolute where they must be. Commands that modify the system are flagged and assume sudo in a lab. No command is to be run on real infrastructure without a backup and approval.
1. Kernel, programs and terminal
The operating system links hardware and programs. The kernel manages the processor, memory, files, devices and network. A user program requests kernel services through system calls: open a file, create a process, send bytes on a socket.
The terminal is a text interface. The shell reads a command, interprets it and launches a program. Bash is one of the most widespread shells. A command consists of a program name, options and arguments. Options often start with - or --.
$ uname -a
Linux lab 6.8.0-45-generic #45-Ubuntu SMP x86_64 GNU/Linux
$ whoami
kelia
$ pwd
/home/kelia
$ echo "$SHELL"
/bin/bash
The shell distinguishes built-in commands, such as cd and export, from external programs, such as ls or grep. It looks for programs in the directories listed by PATH. type shows how a command will be interpreted.
A command's exit code is 0 on success and a non-zero value on failure. $? holds the last command's code. Scripts and the && and || operators rely on this contract. A program that fails silently is hard to diagnose.
Finally, distinguish the interactive shell from a script. A script has no terminal to answer questions; it must read its input, check its arguments and fail cleanly. Commands that ask for confirmation must be avoided or made explicit.
2. Filesystem, paths and inodes
Linux organises files in a single tree starting at /. Main directories have conventional roles: /etc for configuration, /var for variable data, /home for users, /tmp for temporary files, /usr for programs and libraries.
$ ls -la /var/log
$ cd /var/log
$ pwd
/var/log
$ cd ..
$ pwd
/var
An absolute path starts with / and does not depend on the current directory. A relative path starts from the current directory. . is the current directory, .. the parent, ~ the home directory. Use absolute paths in scripts to avoid surprises.
A file is identified by an inode containing its metadata: type, permissions, owner, size, dates and data blocks. The name is a directory entry pointing to the inode. A hard link shares the same inode; a symbolic link contains a path to another entry.
$ stat /etc/hostname
File: /etc/hostname
Size: 12 Blocks: 8 IO Block: 4096 regular file
Device: 801h/2049d Inode: 1234567 Links: 1
Access: (0644/-rw-r--r--) Uid: (0/root) Gid: (0/root)
$ ln -s /etc/hostname /tmp/hostname-link
$ ls -l /tmp/hostname-link
lrwxrwxrwx 1 kelia kelia 12 ... /tmp/hostname-link -> /etc/hostname
Permissions and owner are stored in the inode, not in the name. Renaming a file does not change its inode; moving it within the same filesystem does not change its data. Copying a file creates a new inode.
Finally, filesystems are not all identical. ext4, XFS and Btrfs have different characteristics. A mount attaches a filesystem to a directory. df shows space per filesystem; du shows space used by a tree.
3. Processes, exit codes and signals
A process is a running program, with a PID, a parent PPID, a state and resources. ps shows a snapshot; top or htop refresh the display. A process may be running, sleeping, stopped or a zombie.
$ ps -eo pid,ppid,stat,etime,cmd | head
PID PPID STAT ELAPSED CMD
1 0 Ss 2-03:14:07 /sbin/init
812 1 Ss 2-03:14:05 /usr/sbin/cron -f
1042 1 Ssl 2-03:13:58 nginx: master process
1043 1042 S 2-03:13:58 nginx: worker process
STAT combines letters: S sleeping, R running, Z zombie, s session leader, + foreground. A zombie has finished but its parent has not read its exit code. Too many zombies indicate a parent that does not reap its children.
A signal is a notification sent to a process. SIGTERM (15) requests a clean shutdown; SIGKILL (9) terminates immediately without giving the process time to clean up; SIGHUP (1) is often used to reload configuration. Send SIGTERM first, then SIGKILL if necessary.
$ kill -TERM 1042
$ sleep 2
$ ps -p 1042
PID TTY TIME CMD
$ kill -0 1042; echo $?
1
kill -0 does not kill: it checks the process existence and permissions. A non-zero exit code means the process no longer exists or is not accessible. This check is useful in a script before sending a signal.
Finally, a process inherits its parent's environment and descriptors. Standard descriptors are input 0, output 1 and error 2. Chapter 7 redirections manipulate these numbers. A detached process can continue after the terminal closes.
4. Memory, swap and limits
Each process receives a virtual address space. The kernel translates virtual addresses to physical memory and may move pages to swap. Virtual memory isolates processes and allows exceeding available RAM, at a performance cost.
$ free -h
total used free shared buff/cache available
Mem: 7.7Gi 2.1Gi 3.2Gi 112Mi 2.4Gi 5.2Gi
Swap: 2.0Gi 0B 2.0Gi
$ swapon --show
NAME TYPE SIZE USED PRIO
/swapfile file 2G 0B -2
available is more useful than free: it estimates reclaimable memory, including cache. A large cache is not a problem; Linux uses free memory to speed up I/O. Heavy swap use with low available memory can cause slowdowns.
vmstat 1 shows swapped pages, interrupts and CPU activity. pidstat or top show memory per process. A memory leak appears as consumption that grows without stabilising. Restarting hides the symptom but does not fix the cause.
$ ulimit -a
real-time non-blocking time (microseconds, -R) unlimited
core file size (blocks, -c) 0
open files (-n) 1024
max user processes (-u) 15473
$ systemctl show nginx --property=MemoryMax
MemoryMax=infinity
System limits prevent one process from consuming all resources. ulimit applies to a shell and its children; systemd can apply limits per service. A limit that is too low causes "too many open files" or "cannot allocate memory" errors.
Finally, the kernel OOM killer may terminate a process when memory runs out. dmesg -T | grep -i oom shows traces. A service killed without an apparent explanation must be investigated in kernel logs and in the consumption of other processes.
5. Users, groups and permissions
Each file has an owner, a group and permissions for the owner, the group and others. ls -l shows rwx: read, write, execute. For a directory, x allows entering it and r allows listing its contents.
$ ls -l /var/www/catalogue
-rw-r--r-- 1 www-data www-data 1024 Oct 23 09:00 index.html
drwxr-xr-x 2 www-data www-data 4096 Oct 23 09:00 assets
$ chmod 640 /var/www/catalogue/config.php
$ chown www-data:www-data /var/www/catalogue/config.php
$ ls -l /var/www/catalogue/config.php
-rw-r----- 1 www-data www-data 512 Oct 23 09:05 config.php
Numeric permissions add read 4, write 2 and execute 1. 640 gives rw- to the owner, r-- to the group and nothing to others. 755 is common for a directory; 644 for a non-executable file. Avoid 777, which opens everything to everyone.
A process owner determines its rights. sudo runs a command with another user's privileges, often root. Use it sparingly and check the command before confirming. A permanently open root session increases the risk of an irreversible mistake.
$ id
uid=1000(kelia) gid=1000(kelia) groups=1000(kelia),27(sudo),33(www-data)
$ umask
0022
$ touch /tmp/example
$ ls -l /tmp/example
-rw-r--r-- 1 kelia kelia 0 Oct 23 09:10 /tmp/example
umask removes default permissions at creation. A 022 umask produces 644 for a file and 755 for a directory. A 027 umask is more restrictive and suits sensitive data.
Finally, apply least privilege: a web service must not run as root, a backup script must read only what it needs. ACLs allow finer rights but complicate auditing. Document exceptions and verify them after a deployment.
6. Storage, mounts and disk space
A disk contains partitions or logical volumes, formatted with a filesystem. A mount attaches that system to a directory. lsblk shows disks and mount points; df -h shows space used per filesystem.
$ lsblk
NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINTS
vda 254:0 0 40G 0 disk
├─vda1 254:1 0 39G 0 part /
└─vda2 254:2 0 1G 0 part [SWAP]
$ df -h /
Filesystem Size Used Avail Use% Mounted on
/dev/vda1 39G 28G 9.6G 75% /
du -sh /var/* identifies large directories. du -x stays on one filesystem. find /var -xdev -type f -size +500M looks for large files. A full disk can prevent a service from writing logs or temporary files.
$ sudo du -xh /var | sort -h | tail -5
1.2G /var/lib
2.4G /var/log
6.8G /var/cache
$ sudo find /var/log -type f -name '*.log' -size +100M
/var/log/catalogue/app.log
Deleted files still held open do not free space as long as the process keeps them. lsof +L1 lists these files. Restarting the service or process frees the space. This case sometimes explains a full df when du finds nothing.
Before mounting a new volume, back up and check the mount point. A mount on a non-empty directory hides its contents. Use mount and /etc/fstab with care; an error in fstab can prevent boot.
Finally, monitor space and inodes. df -i shows used inodes; a filesystem can be full in inodes with free space. Many small files, caches and sessions are common causes. Clean with a policy, not at random.
7. Shell: arguments, variables, redirections and pipes
A Bash command can use variables, substitutions and redirections. "$variable" protects spaces; 'text' prevents interpolation; $(command) captures output. Quoting is the first defence against words split by mistake.
$ name="Catalogue Mdjad"
$ echo "$name"
Catalogue Mdjad
$ echo '$name'
$name
$ files=$(ls /var/www/catalogue)
$ echo "$files" | wc -l
> redirects standard output to a file, overwriting it; >> appends; 2> redirects errors; 2>&1 sends errors to standard output; < reads from a file. | connects one command's output to the next command's input.
$ grep -i "error" /var/log/catalogue/app.log > /tmp/errors.txt
$ wc -l < /tmp/errors.txt
42
$ grep -i "error" /var/log/catalogue/app.log 2>&1 | tee /tmp/errors-and-warnings.txt | wc -l
tee writes to the screen and to a file. head and tail limit output; tail -f follows a file live. less pages through a long result. Avoid loading a multi-gigabyte file into an editor.
Environment variables are exported to child processes. export VAR=value makes them available. Do not store secrets in shell history; use a secret manager or a protected file. history keeps commands, including those containing passwords.
Finally, set -e stops the script at the first error, set -u rejects undefined variables and set -o pipefail makes a pipeline fail if any command fails. These options prevent scripts from continuing after a silent error.
8. Text processing and log analysis
grep searches for a pattern. -i ignores case, -r walks a directory, -n shows line numbers, -v inverts the selection. grep -c counts lines. For a complex pattern, use -E or pgrep.
$ grep -c " 500 " /var/log/nginx/access.log
12
$ grep -E " (500|502|503) " /var/log/nginx/access.log | tail -3
203.0.113.10 - - [23/Oct/2026:09:14:02 +0300] "GET /api/products HTTP/1.1" 502 157
$ awk '{print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -nr | head -5
awk splits each line into fields. $1 is the first field, NF the number of fields, NR the line number. An awk script can filter and compute. sed replaces text; sed -i modifies the file, to be used after a backup.
$ sed -n '1,5p' /var/log/catalogue/app.log
$ sed 's/old.example/new.example/g' config.txt > /tmp/config.new
$ awk '$9 == 500 {count++} END {print count+0}' /var/log/nginx/access.log
Logs have different formats. Read the service documentation before analysing columns. An HTTP 500 is not always an application error; a proxy can produce it. Correlate time, URL, request identifier and application logs.
Finally, never modify a production log to "clean" it. Copy it, analyse the copy, then apply rotation or purge according to the retention policy. Logs are evidence and support post-incident diagnosis.
9. Services, systemd and scheduling
systemd starts and supervises services. A unit describes a program, its dependencies, its user and its restart policy. systemctl status shows the state, start starts, stop stops, enable enables at boot, disable disables.
$ systemctl status nginx --no-pager
● nginx.service - A high performance web server and a reverse proxy server
Loaded: loaded (/lib/systemd/system/nginx.service; enabled; preset: enabled)
Active: active (running) since Thu 2026-10-23 08:00:12 UTC; 1h 20min ago
Main PID: 1042 (nginx)
Tasks: 5 (limit: 9451)
Memory: 12.4M
$ journalctl -u nginx --since "1 hour ago" --no-pager | tail -20
journalctl -u filters by unit; -f follows live; --since and --until limit the period; -p err filters errors. A service restarting in a loop shows repeated lines. systemctl reset-failed clears the failure state after a fix.
$ sudo systemctl restart catalogue.service
$ sudo systemctl enable --now catalogue.service
$ systemctl is-active catalogue.service
active
$ systemctl is-enabled catalogue.service
enabled
A custom unit goes in /etc/systemd/system/. It defines ExecStart, User, Restart and optionally EnvironmentFile. After a change, run systemctl daemon-reload. Check the environment file permissions, which may contain secrets.
Scheduled tasks use cron or systemd timers. cron is simple: crontab -e opens the user's table. A systemd timer is more verbose but integrates with logs and dependencies. For a daily backup, prefer a timer or a documented cron with an alert on failure.
# Daily backup at 03:15
15 3 * * * /usr/local/bin/backup-catalogue.sh >> /var/log/backup.log 2>&1
Finally, test the service after a machine reboot, not only after a manual start. A service that works in an interactive session may fail at boot because of a missing path, user or variable. systemctl is-enabled and a controlled reboot confirm it.
10. Networking, ports and diagnostics
A network interface has an IP address, a mask and a gateway. ip addr shows interfaces; ip route shows routes. ss -ltnp lists listening ports and associated processes. A service not listening on the right port will not answer, even if it runs.
$ ip -brief addr
lo UNKNOWN 127.0.0.1/8 ::1
eth0 UP 192.0.2.10/24
$ ss -ltnp
State Recv-Q Send-Q Local Address:Port Peer Address:Port Process
LISTEN 0 511 0.0.0.0:80 0.0.0.0:* users:(("nginx",pid=1042,fd=6))
LISTEN 0 128 0.0.0.0:22 0.0.0.0:* users:(("sshd",pid=712,fd=3))
curl -I shows HTTP headers; curl -v details the connection. dig or getent hosts check DNS resolution. ping tests ICMP, often blocked; its failure does not prove the service is down. Test the port with nc -zv or curl.
$ curl -sS -o /dev/null -w "%{http_code}\n" http://127.0.0.1/
200
$ getent hosts mdjad.net
$ sudo ufw status verbose
Status: active
Logging: on (low)
Default: deny (incoming), allow (outgoing), disabled (routed)
A firewall can block a port even if the service listens. Check the full chain: DNS, route, firewall, listening port, proxy, application. traceroute or mtr help locate a network problem, but may be filtered.
Finally, do not disable a firewall to "test" on an exposed machine. Open only the necessary port, from the necessary addresses, and document the rule. Remove temporary rules after diagnosis.
11. Robust Bash scripts
A script starts with a shebang, for example #!/usr/bin/env bash. Enable set -Eeuo pipefail to stop on error, reject undefined variables and propagate pipeline failures. Use IFS=$'\n\t' for predictable splitting.
#!/usr/bin/env bash
set -Eeuo pipefail
IFS=$'\n\t'
readonly SOURCE="/var/www/catalogue"
readonly DESTINATION="/var/backups/catalogue"
readonly STAMP="$(date +%Y%m%d-%H%M%S)"
if [[ ! -d "$SOURCE" ]]; then
echo "Source not found: $SOURCE" >&2
exit 1
fi
mkdir -p "$DESTINATION"
tar -czf "$DESTINATION/catalogue-$STAMP.tar.gz" -C "$SOURCE" .
echo "Backup created: $DESTINATION/catalogue-$STAMP.tar.gz"
Check arguments and paths before acting. [[ -d ]], [[ -f ]] and [[ -r ]] test existence and rights. realpath normalises a path. Do not build a command with an unquoted variable: a space or special character can change its meaning.
A function groups a step and can be tested. A trap cleans temporary files and reports failure. mktemp -d creates a unique temporary directory. Avoid /tmp/fixed-name, which another process can overwrite.
TMP_DIR="$(mktemp -d)"
cleanup() {
rm -rf "$TMP_DIR"
}
trap cleanup EXIT
trap 'echo "Failure at line $LINENO" >&2' ERR
For a backup, test the restore. An archive that does not extract is not a backup. Check the size, the file list and a witness file. Keep several generations and monitor destination space.
Finally, log the start, end and errors with a timestamp. A silent script is hard to supervise. Use logger to send to the system journal or write to a rotated file. Never log secrets.
12. Synthesis: diagnose and operate
When a server stops responding, proceed from general to specific. Check whether the machine responds, then whether the service listens, then whether the application responds, then what the logs say. This progression avoids changing several layers at once.
$ uptime
09:40:12 up 2 days, 1:20, 1 user, load average: 0.42, 0.55, 0.61
$ df -h /
Filesystem Size Used Avail Use% Mounted on
/dev/vda1 39G 38G 1.0G 97% /
$ systemctl is-active catalogue.service
failed
$ journalctl -u catalogue.service -n 30 --no-pager
A full disk, a stopped service, an expired certificate, an occupied port, a denied permission and a memory leak are common causes. Each cause has a verification command. Note what you observe before fixing; a fix without diagnosis can hide the problem.
After the fix, verify the service, the application and the logs. Remove temporary files created during the intervention. Document the cause, the action and the prevention. A repeated failure indicates a capacity, configuration or monitoring problem.
Backups, updates and monitoring are part of operations. An untested backup, an unplanned update or an unread alert does not protect. Automate what is repetitive, but keep a rollback procedure.
Finally, apply least privilege and the principle of least surprise. A dedicated service account, minimal permissions, readable logs and documented commands make the system safer and more repairable. Terminal mastery is a diagnostic skill, not a contest of obscure commands.
Exercise 1 — Find your way and inspect
In a lab machine, show the current directory, list /var/log with details, then show the metadata of /etc/hostname. Identify the owner, permissions and inode.
Solution
pwd shows the current directory; ls -la /var/log lists entries with permissions, owner and size; stat /etc/hostname shows the inode, permissions 0644, UID and GID. The name is a directory entry; the file identity comes from the inode.
Exercise 2 — Permissions and umask
Create a file, check its permissions with the current umask, then apply 640 and www-data:www-data. Explain who can read, write and execute.
Solution
With umask 022, a new file gets 644: the owner reads and writes, the group and others read. chmod 640 removes read access for others; chown changes owner and group. No execute permission is granted, which suits a configuration file.
Exercise 3 — Analyse a log with pipes
Count HTTP 500 errors in an nginx log, show the last three and list the five most frequent IP addresses. Use grep, awk, sort, uniq and head.
Solution
grep -c " 500 " access.log counts lines. grep -E " (500|502|503) " access.log | tail -3 shows the latest errors. awk '{print $1}' access.log | sort | uniq -c | sort -nr | head -5 counts IPs and sorts by descending frequency.
Exercise 4 — Process and signal
Find a service PID, check it exists with kill -0, send SIGTERM, then verify it stopped. Why not send SIGKILL first?
Solution
ps -eo pid,cmd | grep nginx or pgrep -a nginx gives the PID. kill -0 PID checks existence. kill -TERM PID requests a clean shutdown; ps -p PID confirms. SIGKILL does not let the process close files or finish transactions: it is reserved for a persistent block.
Exercise 5 — Service and scheduling
Create a minimal systemd unit for a script, enable it at boot, check its state and read its logs. Then add a daily schedule and explain where the output goes.
Solution
The unit defines ExecStart, User and Restart; daemon-reload reloads systemd; enable --now enables and starts; journalctl -u reads logs. For cron, output is mailed or redirected to a file with >> ... 2>&1. A systemd timer writes to the unit journal.
Exercise 6 — Robust backup script
Write a script that checks the source, creates a timestamped archive, stops on error and cleans a temporary directory. Test restoring a witness file.
Solution
The script uses set -Eeuo pipefail, checks [[ -d "$SOURCE" ]], creates the destination with mkdir -p, archives with tar -czf and timestamps with date. A trap cleans the temporary directory. Restore is tested with tar -tzf then tar -xzf into an empty directory.
Capstone — a server down
A catalogue server responds poorly. Deliver a diagnostic procedure in at most ten commands: machine state, disk space, memory, service, port, HTTP response, logs. Identify at least three possible causes, the command that distinguishes them and the safe corrective action.
Grading: justified diagnostic order; non-destructive commands; distinction between symptom and cause; verification after correction; backup before modification; documented prevention. A fix without proof of the cause is not complete.
Common mistakes and diagnostic method
Classic mistakes: using sudo without understanding, applying chmod 777, deleting production logs, restarting without a backup, confusing disk space with inodes, forgetting quotes in a path, using kill -9 immediately, disabling a firewall to test, and editing /etc/fstab without validation.
Method: observe, state a hypothesis, test one variable, roll back if needed, then document. Read logs before restarting. Check capacity before adding a process. Test restore before considering a backup valid.
Self-assessment
You must be able to explain the kernel's role, read a path and an inode, interpret permissions, follow a process and a signal, read memory and disk, build a pipeline, analyse a log, manage a systemd service, check a port and write a safe Bash script.
Self-assessment: I can diagnose a full disk; I can explain 644 and 640; I can find a process listening on a port; I can write a script that fails cleanly; I can test a backup. To go further, study containers, monitoring and incident procedures.
References
- GNU Bash Reference Manual, accessed 23 October 2026.
- Linux man-pages, accessed 23 October 2026.
- systemd manual pages, accessed 23 October 2026.
- The Linux Kernel documentation, accessed 23 October 2026.
- Advanced Bash-Scripting Guide, accessed 23 October 2026.
- The Debian Administrator’s Handbook, accessed 23 October 2026.