Linux Lesson 1: Core Fundamentals

Follow a command from the shell to the kernel, then build the Linux skills cloud engineers rely on: filesystem navigation, permissions, users, processes, package management, and command-line text processing. Finish by deploying the sample app as a dedicated system user.
Ubuntu Server 26.04 LTSCompared with 24.04 LTSBash 5.3 · sudo-rs · rust-coreutilsRHEL 10 family comparison (dnf 4)Verified · 2026-11-17
Start here

This is the first course in the DevOps learning path: Linux → Bash → Git → Docker → Kubernetes → Terraform → Ansible → GitHub → GitLab → Azure DevOps → Jenkins → Azure Landing Zone → AKS → Helm → GitOps and Argo CD → Prometheus & Grafana. No prior course is required; basic familiarity with files and directories is enough. Later courses build on the shell, permissions, process management, and package skills covered here. Next, continue with Learn Bash in 8 Hours.

Overall learning objectives
  • Explain the boundary between the kernel and user space, including system calls, processes, and file descriptors. Identify the Linux families, package formats, and support lifecycles used by Ubuntu, Rocky Linux, AlmaLinux, Azure Linux, and Amazon Linux 2023.
  • Trace a command end to end: shell parsing and expansion → executable lookup through PATH → process creation with fork/execve → system calls → permission checks → exit status and wait. The first core animation walks through this sequence.
  • Use Bash quoting, expansion, redirection, pipelines, history, and completion. Use the Filesystem Hierarchy Standard (FHS) to find where configuration, logs, programs, and data belong.
  • Read and set permissions, ownership, umask, ACLs, and special bits (SUID, SGID, and sticky). Apply Linux's access-check order to determine whether a user can reach or modify a file.
  • Manage users, groups and sudo: /etc/passwd, /etc/shadow, /etc/group, /etc/sudoers.d/, understand Ubuntu 26.04 default sudo-rs and traditional sudo difference.
  • Observe and control process: ps, top, /proc, signals, job control (&, jobs, fg, bg, nohup).
  • Use apt (deb822 .sources format) and dnf to install, query, fix, and roll back software packages, and understand warehouse signatures and Signed-By.
  • Analyze the logs with the grep / sed / awk / sort / uniq / cut / xargs combination pipeline; do a final system readiness review and manually run myapp (port 5000) as system user myapp in /opt/myapp - Lesson 2 will turn this into myapp.service.

1-hour time allocation table

#TimeModuleCore contentAnimation/InteractionExperiment (~/linuxlab)
0Before classEnvironment preparationMultipass creation linuxlab (Ubuntu 26.04 LTS), administrator labadmin, working directory, optional rhellabEnvironment self-check listcan log in as labadmin and sudo
100–06Linux ArchitectureKernel/user space/system call/release family and support cycleCore Animation 1: The whole process of executing a commanduname, /etc/os-release, strace See system calls
206–13Shell and FHSBash parsing with 7 types of expansion, quotes, redirects, pipes, PATH, FHS directory responsibilitiesShell expansion step-by-step demonstrationBuild ~/linuxlab directory tree, practice redirection
313–21Permissions and ACLrwx, ownership, umask, ACL and mask, SUID/SGID/sticky, capabilitiesCore Animation 2: Permission determination + chmod / umask calculatorShared directory /srv/share and ACL
421–28Users, groups and sudopasswd / shadow / group, system user, sudoers.d, sudo-rssudo authorization processCreate user alice / bob, group devs, restricted sudo rules
528–35Processes and signalsProcess tree, status, /proc, signals, job control, nohupProcess state machine + signalingForeground and background switching, SIGTERM vs SIGKILL
635–42Software package managementapt and deb822 sources, signatures, dpkg; dnf and .repo; version fixation and rollbackapt install full processInstalling redis-server, python3-venv, query and fixation
742–50Text processinggrep regular, sed replacement and in-place editing, awk fields and aggregation, sort / uniq / xargsPipeline step-by-step simulatorAnalysis of access logs: Top IP, 5xx, P95
850–60Readiness review and troubleshooting12 system readiness review; the order of locating common errorsReadiness scorecard + interactive troubleshooting treeDeliberately create 4 faults and fix them
—After classCheat Sheet · Comprehensive ExperimentManually deploy and accept the myapp user in /opt/myappFinal Test (12 Question)myapp returns /healthz

Knowledge Coverage Matrix

Target skillsM1M2M3M4M5M6M7M8Key commandsExperimental
Explaining kernel/user space/system calls✓✓✓·✓··✓uname -r, straceM1
Identifying release and support period✓····✓·✓/etc/os-release, pro statusM1, M8
Bash expansion, quotes, redirection, pipes✓✓··✓·✓✓set -x, type, 2>&1M2, M7
FHS Locating files·✓✓✓·✓·✓ls /etc /var/log, dpkg -LM2, comprehensive experiment
Permissions, umask, ACL, special bits✓·✓✓···✓chmod, setfacl, namei -lM3, comprehensive experiment
User, group, sudo··✓✓···✓useradd, visudo, sudo -lM4, comprehensive experiment
Process, signal, job control✓✓··✓··✓ps, kill, jobsM5, comprehensive experiment
apt / dnf and warehouse✓····✓·✓apt, dpkg, dnfM6, comprehensive experiment
Text processing and log analysis·✓····✓✓grep, sed, awkM7
System readiness review and troubleshooting··✓✓✓✓✓✓df -h, ss -ltnp, journalctlM8 troubleshooting tree

What is excluded from this lesson (and where to learn it)

TopicWhy not in this lessonWhere to learn
systemd unit, journald, LVM, mount, network, SSH Reinforcement, cron / timerBelongs to system management, you need to master the basics of this course firstLesson 2: System management and production readiness
Cloud Linux: cloud-init, managed disks, Entra ID login, Azure Monitor AgentAzure subscription requiredLesson 3 (Azure)
EC2, Amazon Linux 2023, IMDSv2, SSM, CloudWatch AgentAWS account requiredLesson 4 (AWS)
Bash script engineering (set -euo pipefail, trap, ShellCheck), PackerBelongs to automationLesson 5
SELinux / AppArmor, firewall, PAM, auditd, namespaces and cgroupsSecurity and kernel mechanismsLesson 6 Lesson; from the container perspective, see Docker Lesson
Performance analysis, strace / perf / eBPF in-depth, startup failureIn-depth troubleshootingNo. 7 class; for indicator monitoring, see Prometheus & Grafana class
Batch configuration of multiple hostsBelongs to configuration managementAnsible course

How to use this courseware

10 paginations for each module
Principle · Diagram · Animation · Command · Experiment · Production case · Troubleshooting · Quizzes · Voice · Video. It is recommended to read "Principle" and "Animation" first, and then do "Experiments" on linuxlab . The "Execute a Command" animation in Module 1 and the "Permission Determination" animation in Module 3 are the two main threads of the entire course, and each subsequent module will return to them.
Learning Progress
Test score ≥ 70% or click "Mark this module completed" will be counted as progress and saved in the local storage of this browser (it will be cleared after refreshing when the browser prohibits local storage).
Chinese Voice
The "Voice" tab uses the browser's built-in Web Speech API (en-US) to read the explanation script, and English terms are pronounced in en-US; the explanation script can still be read when there is no Chinese voice package, or it can be handed over to the TTS tool to generate audio.
Release NotesVerification date 2026-11-17. The lab VM uses Ubuntu Server 26.04 LTS (Resolute Raccoon, released on 2026-04-23, standard security maintenance until 2031-05, ESM until 2036-05), GA kernel Linux 7.0, systemd 259, APT 3.1(apt-key Removed),Bash 5.3, Python 3.14. 26.04 defaults sudo-rs as sudo, rust-coreutils(uutils)provides most of the core tools (cp, mv, rm, df, true Still from GNU). If you are using 24.04 LTS (kernel 6.8, systemd 255, APT 2.7, Python 3.12, GNU coreutils, traditional sudo), the commands in this lesson are also applicable, and the differences will be marked with "24.04:". The RHEL system is compared to Rocky Linux / AlmaLinux 10.x (RHEL 10.3 was released on 2026-11-11; the latest official version of Rocky at the time of verification is 10.2), and the package manager is dnf 4.20 (dnf5 is currently used in Fedora). Upstream kernel: stable 7.3.x, longterm 6.18/6.12/6.6/6.1/5.15/5.10.

Module 0 · Environment Preparation (completed before class)

Create a local experimental virtual machine linuxlab (Ubuntu Server 26.04 LTS), administrator user labadmin, working directory ~/linuxlab. Lessons 1–4 are all conducted on this machine (or its “twin” in the cloud)
Before class ≈ 15 minutesRun locally · FreeOnly do destructive operations on the lab machine
Prerequisites
  • A Windows 10/11, macOS or Linux computer with available memory ≥ 8 GB (4 GB for virtual machine), available disk ≥ 25 GB, CPU supports and hardware virtualization (VT-x / AMD-V in BIOS/UEFI) is enabled.
  • Can install software as an administrator. No cloud account required (only required for Lessons 3 and 4).
  • This course is the first course in the route and has no prerequisite courses; Lesson 2 will directly reuse the linuxlab, labadmin, ~/linuxlab and /opt/myapp of this course.

Unified agreement for the whole course (consistent for lessons 1–4)

ProjectAgreed valueExplanation
Experimental machineHostname linuxlab, Ubuntu Server 26.04 LTS (24.04 also available)2 vCPU / 4 GB RAM / 20 GB disk
Adminlabadmin (in the sudo group)Use it for daily operations, do not log in directly with root
Working directory~/linuxlab (i.e. /home/labadmin/linuxlab)Script, sample log, myapp source code
Example applicationmyapp (Flask + gunicorn + Redis), port 5000, /healthzSystem user myapp, installation directory /opt/myapp, virtual environment /opt/myapp/venv, configure /etc/myapp/myapp.env
RHEL system control (optional)Host name rhellab, Rocky Linux or AlmaLinux 10.xOnly used for comparison dnf / firewalld / SELinux
Lesson 2The same linuxlabturn myapp into myapp.service; LVM Experiment with a loop device (loop) to simulate an additional disk
Lesson 3 / 4Azure: rg-linux-lab / canadacentral / vm-linux-lab; AWS: ca-central-1 / Name=linux-lab / Amazon Linux 2023Use cloud-init / user data to reproduce the local myapp deployment

Method A (recommended): Multipass

Multipass is Canonical's lightweight virtual machine manager (latest version 1.17.1 at time of verification), which uses Hyper-V or VirtualBox on Windows, the Apple virtualization framework on macOS, and QEMU/KVM on Linux. After installing from canonical.com/multipass/install:

 data-l="bash"
 class="out" data-l="Expected output (example)"

launch's -c/--cpus (default 1), -m/--memory (default 1G, minimum 512M), -d/--disk (default 5G, minimum 1G) are all from the official CLI reference; the image parameter can be a codename, alias or version number. Multipass will set the instance name to the hostname, so the hostname is linuxlab. If you can only use 24.04, replace 26.04 with 24.04.

Create administrator labadmin

The default user for Multipass is ubuntu. We create labadmin as agreed in the whole course and use it in the future:

 data-l="bash"
 class="out" data-l="Expected output (example)"
 data-l="bash"

< redirection is not available in Windows PowerShell. You can change it to: Get-Content $HOME\.ssh\linuxlab.pub | multipass exec linuxlab -- sudo -u labadmin bash -c '...', IP directly from multipass info linuxlab Copy.

Method B: Hyper-V / VirtualBox / VMware + Official ISO

  • Download Ubuntu Server 26.04 LTS from ubuntu.com/download/server ISO, create a new virtual machine: 2 vCPU, 4 GB memory, 20 GB disk (for Hyper-V, select Generation 2 virtual machine and set the secure boot template to "Microsoft UEFI Certificate Authority").
  • In the installation wizard: fill in linuxlab for the server name, labadmin for the user name (the first user created by the installer is automatically in the sudo group), and check Install OpenSSH server.
  • Just use NAT/default switch for the network; when you need to SSH from the host, use bridge or port forwarding (VirtualBox: NAT port forwarding 2222 → 22).

Method C: WSL2 (available, but with restrictions)

  • Use wsl --list --online to view the installable distribution names (subject to the output), then wsl --install -d ; fill in labadmin for the user created at first startup. The host name defaults to the Windows host name, which can be set in the [network] section of /etc/wsl.conf. hostname = linuxlab.
  • systemd: WSL2 requires [boot] systemd=true in /etc/wsl.conf to use systemd as PID 1 (newer Ubuntu WSL distributions have it written by default); use ps -p 1 -o comm= Check, the output should be systemd. Lesson 2 relies heavily on systemd.
  • Kernel and disk: WSL2 uses the kernel maintained by Microsoft (uname -r with microsoft-standard-WSL2). The system disk is a virtual VHDX and there is no real partitioning and boot process. Lesson 2's LVM switch to a loopback device can still be completed, but GRUB, boot failures, etc. (Lesson 7) cannot be practiced in WSL2.
  • The Windows file system is mounted at /mnt/c, and the permission bits there are simulated: The permission experiments of module 3 must be done in Linux's own directory (such as ~/linuxlab).

Initializing the working directory and tools

The following are executed in linuxlab with labadmin:

 data-l="bash"
 class="out" data-l="Expected output (example)"

acl provides getfacl/setfacl (module 3), strace is used to observe system calls (module 1), psmisc provides pstree/killall (module 5), and lsof is used for troubleshooting (module 8). These packages may have been pre-installed in the cloud image. apt will prompt "is already the newest version", which is normal.

Generate sample log (used in module 7)

 data-l="bash"
 class="out" data-l="Expected output (example)"

Optional: RHEL system comparison machine rhellab

Use only when you need to compare dnf, firewalld, and SELinux. Download 10.x DVD / Minimal ISO from rockylinux.org or almalinux.org to install in Hyper-V / VirtualBox: Hostname rhellab, create user labadmin and check "Make this user administrator" (that is, join the wheel group), 2 vCPU / 2 GB / 20 GB. Note EL10 requires an x86-64-v3 class CPU (AlmaLinux also provides an x86-64-v2 build). Multipass does not provide Rocky / Alma mirrors.

Environment self-check checklist

Fees, permissions and cleanupAll runs locally, no cloud fees. Multipass requires administrator rights to install; labadmin has sudo in the virtual machine, which is equivalent to root - the destructive operations in this lesson (changing permissions, deleting users, killing processes) should only be done in linuxlab . Do not copy them on work computers or production servers. Pause: multipass stop linuxlab; Snapshot: multipass snapshot linuxlab --name before-lesson1 (the instance must be in stopped state); Complete deletion: multipass delete linuxlab && multipass purge. Continue to use linuxlab in Lesson 2. Please do not delete it after completing this lesson.

Module 1 · Linux Architecture: Kernel, User Space and Distribution

00:00 – 06:00 · The program lives in user space and can only request kernel services through system calls; distribution = kernel + user space + package management + support commitment
6 minutesLinux 7.0 (26.04 GA kernel)Core Animation 1★★★★★
Learning Objectives
  • Explain clearly the relationship between kernel, user space, system calls, processes, file descriptors, init (systemd), as well as the meaning and boundaries of "everything is a file".
  • Tell us the whole process of executing a command: parsing and expansion → PATH search → fork (clone) → execve → kernel permission check and loading → system call → exit_group → parent process wait4 gets $?.
  • Distinguish the package format, package manager, release rhythm and support cycle of Debian/Ubuntu, RHEL series, Azure Linux, and Amazon Linux 2023, and know how to identify it on a strange machine within 10 seconds.
  • Use uname, /etc/os-release, /proc, strace to verify the above concepts on the lab VM.
Prerequisite knowledge:None. Importance:★★★★★ (the entire 8 hours are built on this model)

What: What layers does Linux consist of

Strictly speaking, Linux is a kernel (Linus Torvalds Released in 1991, GPLv2). The "Linux system" we talk about every day is kernel + user space: C library (glibc), init system (systemd), Shell (bash), core tools (coreutils), package managers and thousands of applications. The one that selects, compiles, packages, tests, and maintains them for a long time is the release.

LevelWhat is itHow to see it on linuxlab
Hardware/virtual hardwareCPU, memory, disk, network card; in the virtual machine, it consists of Hyper-V / KVM emulationlscpu, lsblk, ip link
Kernel spaceRun at CPU privilege level (x86 ring 0): process scheduling, memory management, virtual file system (VFS), network protocol stack, device driver, permission checking, namespaces / cgroupsuname -r, lsmod, /proc, /sys
System call interfaceThe only front door for user space to enter the kernel: openat, read, write, clone, execve, wait4, kill… About x86-64 400strace -c ls
C library glibcpackages system calls into functions such as open(), printf(); the dynamic linker ld-linux-x86-64.so.2 is responsible for loading shared librariesldd /usr/bin/bash
init: systemd(PID 1)The first user space process started by the kernel, responsible for pulling up all services and recycling orphan processes (detailed in Lesson 2)ps -p 1 -o pid,comm, systemctl --version
User space programsbash, ls, sshd, python, myapp... all run at the non-privileged level (ring) 3), memory isolation from each otherps -ef

Why: Why separate kernel and user space

  • Isolation and stability: The crash of the user program only affects itself (receiving SIGSEGV) and will not bring down the kernel; a kernel panic (kernel panic) is a complete machine failure.
  • Security: Accessing the disk, network, and memory of other processes must go through system calls. The kernel checks the identity (UID/GID, capabilities) and permissions at the entrance - this is where the permission determination of module 3 occurs.
  • Portable: the same ls binary, regardless of whether the underlying is NVMe or a network disk, VFS hides the difference behind openat/read.

How: What happens when a command is executed (core animation of this module)

  1. Reading and parsing: bash reads a line and splits it into words and commands according to quotation marks, whitespace and operators (| > &&).
  2. Expansion: Curly brackets → tilde → Parameters and variables / Arithmetic / Command substitution → Word splitting → Pathname (wildcard) → Dequotation marks (detailed in Module 2).
  3. Command search: Aliases, functions, built-in commands (cd, echo, type) are directly executed in the bash process; otherwise, check the hash table and press $PATH to find the executable file from left to right.
  4. fork: bash calls clone (glibc's fork()) to copy the child process; copy-on-write makes it take almost no time.
  5. Child process preparation: Perform redirection in the child process (openat + dup2 points fd 1 to the file), resume signal handling, and then call execve.
  6. Kernel: Permission checking and loading: Each directory on the path requires x (search) permissions, the file itself requires x permissions and the file system is not mounted with noexec; read the ELF header (or find the interpreter with the #! line), map the code segment, and hand it over to the dynamic linker. On failure, execve returns ENOENT / EACCES.
  7. Run: The program reads and writes files and networks through system calls; each call will go through the kernel's permission check again.
  8. Exit and recycling: The program calls exit_group(status), and the kernel sends SIGCHLD to the parent process; bash gets the status in wait4 and writes $?: 0 success, 1–125 program customization failure, 126 Found but unable to execute, 127 Command not found, 128+N terminated by signal N (Ctrl+C is 130). The child process is briefly in the zombie state (Z) before the parent process is recycled.

When: How to choose a distribution version

DistributionFamily/Package FormatPackage ManagerCurrent Version and Support (2026-11-17 Verification)Typical Scenario
Ubuntu Server LTSDebian-based / .debapt + dpkg26.04 LTS (2026-04) standard supported to 2031-05, ESM to 2036-05; 24.04 LTS standard supported to 2029-05; one LTS every two years, with 9 in between Month's transition version (latest 26.10)The most common general-purpose Linux, Kubernetes nodes, development machines on the cloud
RHEL / Rocky / AlmaLinuxRed Hat system / .rpmdnf (EL10 is dnf 4.20) + rpmRHEL 10.3 (2026-11-11); Rocky 10.2, AlmaLinux 10.x; each major version has a life cycle of approximately 10 years, and minor versions approximately every 6 monthsEnterprise, software that requires commercial support and certification (database, SAP)
Azure LinuxMicrosoft maintenance / .rpm3.0 uses tdnf3.0 official version; 4.0 in Entering public preview in mid-2026 (if it has been GA, please refer to the official document)AKS nodes, container hosting and thin workloads on Azure
Amazon Linux 2023Fedora-based AWS distribution / .rpmdnfStandard support to 2027-06-30, maintenance period until 2029-06-30; minor versions are released quarterly, each version corresponds to a new AMI and a locked warehouse versionEC2, ECS, Lambda and other AWS workloads (Lesson 4)

You will also encounter: Debian (Ubuntu upstream), Fedora (the upstream direction of RHEL), SUSE / openSUSE (zypper), Alpine (apk, musl libc, common in container images). Selection principles: What the team is familiar with, what the supplier has certified, what the cloud platform defaults to, and whether the support cycle covers the system life.

Key changes in Ubuntu 26.04 LTS relative to 24.04 (relevant to this lesson)

Components24.04 LTS26.04 LTSHow it affects you
Kernel (GA)6.87.0The version number jumps to 7, but the number is rolled, and the user space interface remains compatible
systemd255259 (cgroup v1 removed)Old container runtimes/monitoring agents that rely on cgroup v1 need to be upgraded
sudosudo(sudo.ws)sudo-rs (original renamed sudo.ws)The prompt changes to [sudo: authenticate] Password:; does not support I/O logs and sudoreplay, no sudo-ldap (module 4)
Core-ToolsGNU coreutilsrust-coreutils (uutils); cp/mv/rm/df/true Still GNUThe wording of individual options or error messages may be different; the GNU version is provided with the gnu prefix (such as gnuls) and can be switched as a whole (module 2)
APT2.73.1 (new solver, apt history-list, apt-key removed)The apt-key add in the old tutorial no longer works, use Signed-By instead (module 6)
Python / OpenSSH3.12 / 9.6p13.14 / 10.2p1myapp's virtual environment uses 3.14; DSA keys are no longer supported
Time synchronizationsystemd-timesyncdchrony (new installation)Time synchronization experiment for lesson 2
Common misunderstandings① "Linux is Ubuntu" - Linux is the kernel and Ubuntu is the distribution; the same kernel version can appear in many distributions. ② "root can do everything" - root (UID 0) has all capabilities by default, but is still subject to SELinux/AppArmor, read-only mounting, immutable attributes, etc. For example, execve a file without any x bits, root will also get Permission denied. ③ "cd is a program" - cd must be a Shell built-in command, because changing the working directory of the child process will not affect the parent process. ④ "The command cannot be found because it is not installed" - it may also be a different PATH (sudo Use secure_path), spelling error, or lack of x permissions (that is 126 instead of 127). ⑤ "Kernel version 7.0 means big changes" - The major version number of Linux only rolls after the minor version number becomes larger, which does not mean incompatibility.

Architecture diagram: linuxlab layering

User space User space (ring 3) · Each process has an independent virtual address space systemdPID 1 · init sshd → bashlabadmin login Shell ls / grep / awkcoreutils Other tools gunicorn (myapp)User myapp · :5000 redis-serverUser redis · :6379 apt / dpkgPackage management glibc (open / read / fork / execve packaging) · ld-linux-x86-64.so.2 dynamic linkerProgram → Library function → syscall instruction (x86-64)/svc (arm64) System call: the only front door (openat · read · write · clone · execve · wait4 · kill · socket...) Kernel space Kernel space (ring 0) · Linux 7.0 (Ubuntu 26.04 GA) Process schedulingtask_struct · Signal Memory ManagementPage Table · Page Cache · OOM VFS + Permission Checkext4 · xfs · proc · sysfs Network Protocol StackTCP/IP · netfilter Security and Isolationcaps · LSM · ns · cgroups Device driver (virtio-net · virtio-blk / hv_storvsc · NVMe)Provided by module (lsmod) or compiled into the kernel (Virtual) Hardware: 2 vCPU · 4 GB RAM · 20 GB disk · Virtual network cardMultipass → Hyper-V / QEMU-KVM / Apple Virtualization
Figure 1-1 A program can only ask the kernel for services through system calls; the kernel checks the identity and permissions at the entrance of each call

Flow chart: the lifeline of a command

AnalysisWord · OperatorsQuotes Expand~ $VAR $( )* ? [ ] FindAlias·Function·Built-inhash · $PATH forkclone()Copy on write Redirectopenat · dup2(in child process) execvePermissions · ELF#! Interpreter Runsyscalls $?wait4 Parent process bash (without fork) Built-in commands: cd · export · echo · type · read Shell function, variable assignment exec command: no fork, directly replace with new program bash Failure point and exit code Find failure → “command not found” → 127 Redirect failure → “bash: file: Permission denied” → 1 (the command was not executed at all) execve EACCES → 126 · Failed during program operation → Program customization (ls is 2) · Signal N → 128+N
Figure 1-2 The first three steps are completed in the bash process; the child process after fork is redirected first, and then execve becomes the target program

Core Animation 1: The entire process of executing a command

Take the command entered by labadmin on linuxlab as an example. The upper half is user space (bash and subprocesses), and the lower half is the kernel; the right side shows the real system calls (simplified) that can be seen by strace -f, and the lower terminal shows the output seen by the user and $?. Switch scenes to see at which step the command failed and what the exit code was.

User space ① ParsingWord · Operator · Quotes ② Expand~ · $VAR · *.log ③ Command searchBuilt-in · hash · PATH ④ forkclone() → child process ⑤ Subprocess preparationRedirect openat/dup2 ⑧ wait4 → $?— Kernel space (system call entry · permission check) ⑥ execvex permission · ELF · ld.so ⑦ Run: system callopenat · getdents64 · write · exit_group
strace -f perspective (simplified)
 class="out" data-l="syscalls" id="a1q" style="min-height:200px;white-space:pre-wrap"
Ready. Select the scene and click "Play" or "Next".
labadmin@linuxlab:~$
The real mechanism corresponding to the animationbash completes parsing, expansion and command search (search_for_command) in the parent process, and then forks; even if the command cannot be found, bash will be called in the child process command_not_found_handle (Ubuntu command-not-found prompt) and exit with 127. The redirection is done in the child process, so the redirection in sudo ls > /etc/x is still done by your own bash to open the file as labadmin - this is the source of "sudo but Permission denied". execve 's permission checks follow path_resolution(7): every directory on the path requires search(x) permission; even if it has CAP_DAC_OVERRIDE, execution is only allowed if the file has at least one x bit. You can see these calls for yourself with strace -f -e trace=clone,execve,openat,wait4 bash -c '…' .

Command table

CommandFunctionKey parameters/description
uname -a / uname -rKernel name, version, architecture-r only looks at the kernel version, -m looks at the architecture
cat /etc/os-releaseDistribution identity (all modern distributions have it)ID, ID_LIKE, VERSION_ID, VERSION_CODENAME
hostnamectlHost name, OS, kernel, virtualization typeShow Virtualization: microsoft/kvm
type / command -vDetermine whether a name is an alias, function, built-in, or external programtype -a ls List all candidates
straceTrace system calls-f Trace child processes, -e trace= filtering, -c statistics
lddView dynamically linked shared librariesOnly used for trusted binaries
echo $?Exit code of the previous commandIt will be overwritten every time a command is executed
pro statusUbuntu Pro / ESM status (Ubuntu)Free for up to 5 machines for individuals
 data-l="bash"
 class="out" data-l="Expected output (example, 26.04 on Hyper-V)"

How to verify: Determine the distribution version in the script should read ID / ID_LIKE of /etc/os-release (ID="rocky", ID_LIKE="rhel centos fedora" for Rocky, ID="amzn" for Amazon Linux 2023), do not parse uname or /etc/issue. Common mistakes: Treating the kernel minor version number (such as -15-generic) as the release version. Production use: Asset inventory, patch baseline verification.

 data-l="bash"
 class="out" data-l="Expected output (example, excerpt)"

The number is different every time. The failure of openat in the errors column is usually caused by the dynamic linker trying multiple paths in sequence to find the library or language file, which is normal.

 data-l="bash"
 class="out" data-l="Expected output (example)"

Goal: Identify the system identity and see "fork → execve → wait4" with strace. Environment:linuxlab, labadmin. Fees: None.

Identification system:
 data-l="bash"
 class="out" data-l="Expected output (example)"

. /etc/os-release Use source to read the variables in the file into the current Shell - this file itself is a legal Shell variable assignment. /sbin/init is a symbolic link to systemd.

Observe fork / execve / wait4:
 data-l="bash"
 class="out" data-l="Expected output (example, PID different)"

Pay attention to four details: ① ~ has been expanded into /home/labadmin before execve; ② openat occurs in child process 4121, earlier execve; ③ The open mode 0666 will be filtered by umask (module 3); ④ echo done is a built-in command and does not generate clone/execve. On 26.04 /usr/bin/ls from rust-coreutils, the system call order is generally the same as the GNU version, details may differ slightly.

Experience 126 vs. 127:
 data-l="bash"
 class="out" data-l="Expected output (example)"
Compare RHEL lineage (optional, in rhellab) : cat /etc/os-release ID="rocky" or ID="almalinux", ID_LIKE="rhel centos fedora"; uname -r Shaped like 6.12.0-…el10…x86_64 (EL10 is based on the 6.12 LTS kernel and will be backported with patches in the long term).
Cleanup: rm ~/linuxlab/tmp/trace.txt (retain deploy.sh, used by module 3).

Case 1: "Permission denied even after sudo"

Problem: When the operation and maintenance script executes sudo echo "vm.swappiness=10" > /etc/sysctl.d/99-app.conf, Permission denied is reported. Root cause: The redirection causes the current user's Shell to open the file first in the child process after the fork, and sudo only elevates echo. Method:echo "vm.swappiness=10" | sudo tee /etc/sysctl.d/99-app.conf > /dev/null, or sudo sh -c '…'. Prevention: Make "sudo + redirection" a check item during code reviews.

Case 2: The distribution version is determined to be hard-coded, causing the script to fail on the new system

Problem: The installation script uses grep -q "CentOS" /etc/redhat-release to determine the RHEL system and goes to the wrong branch after switching to Rocky / AlmaLinux. Method: Read the ID and ID_LIKE of /etc/os-release, and press the "family" branch (*rhel*|*fedora* → dnf; *debian* → apt). Limitations: Amazon Linux 2023's ID_LIKE="fedora" is not completely consistent with the RHEL package name and needs to be tested separately.

Case 3: Audit issues caused by expiration of support cycle

Issue: The audit found that multiple servers are still running Ubuntu 20.04, standard support has ended in 2025-05, and security updates are only available through Ubuntu Pro (ESM). Method: Enable Pro for a short period of time to obtain ESM patches, and formulate a migration plan to 24.04 / 26.04; record the VERSION_ID and EOL date of each machine in the asset system. Prevention: For new projects, select the latest LTS and list "release EOL earlier than the system retirement date" as a blocking item in the architecture review.

Common errors and solutions

bash: xxx: command not found (exit code 127)

Cause: The command is spelled incorrectly, the software is not installed, the directory is not in $PATH, or PATH is replaced by secure_path under sudo.

 data-l="bash"

Fix: Install the package, use an absolute path, or add the directory to PATH (write ~/.bashrc or ~/.profile).

bash: ./script.sh: Permission denied (exit code 126)

Cause: The file does not have the x bit; or the file system is mounted with noexec (such as /tmp in some systems); or a directory on the path lacks x permissions.

 data-l="bash"

Fixed: chmod u+x script.sh; use bash script.sh to explicitly call the interpreter during noexec, or change to a directory that allows execution.

bash: ./tool: cannot execute: required file not found / No such file or directory (the file obviously exists)

Reason:execve returns ENOENT not the file itself, but the interpreter or dynamic linker it requires: the first line of the script #!/usr/bin/python points to a path that does not exist, or the file has a Windows newline (#!/bin/bash\r), or the binary was compiled for another architecture / musl.

 data-l="bash"

Fixed: sed -i 's/\r$//' tool to remove CR; fix shebang to #!/usr/bin/env python3; use the correct architecture build.

Exec format error

Cause: The binary architecture does not match (running an arm64 program on x86-64), or the script is missing a shebang and is exec'd directly by a non-shell program.

 data-l="bash"

Fix: Download the version corresponding to the architecture (x86_64/amd64 or aarch64/arm64); add #!/bin/bash to the first line of the script.

Command line operation questions
1. Use a command to output "release ID/version/kernel version", for example ubuntu 26.04 7.0.0-15-generic.
 data-l="bash"

Use sub-shell brackets to avoid contaminating the current shell with os-release variables.

2. Prove that cd will not spawn new processes, but ls will.
 data-l="bash"

Only see bash's own execve, a clone and an execve of /usr/bin/ls; cd and true (built-in) do not generate any clone/execve. Adding ; true at the end is to prevent bash from optimizing the last simple command of the -c string by "executing directly without fork".

Scenario Analysis Question
A colleague ran backup.sh in cron. The manual execution was normal, but "aws: command not found" was reported in cron. Please analyze the cause and suggest two fixes.

The shell launched by cron does not read interactive configuration files, PATH usually only has /usr/bin:/bin, and the aws CLI is installed in /usr/local/bin or ~/.local/bin. Command lookup failed in PATH → 127. Fixes: ① Use absolute paths in scripts or export PATH=/usr/local/bin:/usr/bin:/bin at the beginning; ② Set PATH=… at the top of crontab. A better approach is to use systemd timer from Lesson 2 and declare the environment explicitly. When troubleshooting, add echo "$PATH" >> /tmp/backup-debug.log at the beginning of the script.

Verified teaching video

▶
Linux in 100 Seconds — Fireship
English · About 2 minutes · A quick overview of the kernel, user space, and distributions
▶
Introduction to Linux – Full Course for Beginners — freeCodeCamp.org
English · A complete introductory course, covering most modules of this course; the distribution version shall be subject to this course

Official document

Video storyboard script (about 90 seconds)

This courseware cannot directly generate video/MP3. Storyboards and explanation scripts have been provided, which can be generated by video tools.

Shot 1 · 0–15s
Screen: A horizontal dotted line divides the screen into upper and lower halves, with "User Space" written above and "Kernel" written below.
Narration: The Linux system is divided into two halves, with the program living on top and the kernel living below. There is only one door in the middle, called the system call.
Shot 2 · 15–40s
Screen: Entering in the terminal ls -l *.log > list.txt, the words are cut and the asterisks become three file names.
Narration: After pressing Enter, bash parses and expands first, and the tildes and asterisks have become real paths here.
Shot 3 · 40–70s
Screen: bash copies a child process, the child process opens list.txt, and then enters the kernel through the dotted line. The kernel checks the x permission and then loads ls.
Narration: bash forks first, the child process handles the redirection, and then execves, the kernel checks permissions and loads the new program.
Shot 4 · 70–90s
Screen: ls ends, number 0 flies back to bash, displayed $? = 0; 126, 127, 130 listed next to it.
Narration: The program exits, and the parent process uses wait to get the exit code. Remember: 126 cannot be executed, 127 cannot be found, 128 plus N is killed by a signal.
Or score ≥ 70% on the Quiz

Module 2 · Shell and File System Hierarchy (FHS)

06:00 – 13:00 · bash "rewrites" your command before execution: expansion, quotation marks, redirection; where the file is placed is determined by FHS
7 minutesBash 5.3Quotation marks are the most common source of bugs★★★★★
Learning objectives
  • Speak bash in order Expansion of: braces, tildes, parameters/variables, arithmetic, command substitution, word splitting, pathname expansion, dequotation, and the ability to predict the parameters that a command will ultimately pass to the program.
  • Use single quotes, double quotes, and backslashes correctly; master the order rules of <<< | and redirection.
  • Understand the differences between configuration files, PATH, environment variables and Shell variables read by login shell and interactive shell.
  • Press FHS to tell the responsibilities of /etc, /var, /usr, /opt, /srv, /run, /proc, /tmp, and know where each file of myapp should be placed.
Prerequisite knowledge:"Execute a command" of module 1. Importance:★★★★★

What: Shell is

Shell is an ordinary user space program, responsible for reading commands → rewriting (expanding) → starting programs → collecting exit codes. The interactive default shells of Ubuntu and RHEL systems are both bash (5.3 in 26.04); Ubuntu's /bin/sh points to the smaller and faster dash, and RHEL's /bin/sh points to bash - so do not use bash-specific syntax (such as [[ ]], array).

Bash expansion order (bash manual "Shell Expansions")

#ExpansionExampleResult
1Braces bracemkdir -p app/{bin,etc,log}Three parameters app/bin app/etc app/log
2tilde tilde~/linuxlab, ~myapp/home/labadmin/linuxlab, myapp's home directory
3Parameters and variables, arithmetic, command substitution (from left to right)$HOME, ${PORT:-5000}, $((2*3)), $(date +%F)Values are substituted
4Word splittingUnquoted expansion results are split by $IFS (space, tab, newline)f="my file"; ls $f → two parameters
5Pathname pathname (glob)*.log, ?, [0-9]Replace with matching file name in alphabetical order; default to unchanged if no match
6Quote removalRemove unescaped \ ' "The program cannot see the quotation marks
Quotation marksEffectWhen to use
'Single quotation mark'Complete literal, no expansionawk program, sed expression, string containing $
"Double quotes"Allow $variable, $( ), \, but prevent word splitting and wildcardsenclose all variables in double quotes by default: "$file"
\ BackslashEscapes the next character; \ at the end of the line indicates line continuationLong command line break

Redirection and pipe

WritingMeaning
cmd > f / cmd >> fStandard output (fd 1) overwrites/appends to f
cmd 2> err.logStandard error (fd 2) writes to file
cmd > all.log 2>&1First point 1 to the file, then let 2 copy 1 → Both enter files. The order is reversed (2>&1 > f) when 2 still points to the terminal
cmd &> all.logbash abbreviation, equivalent to the previous line
cmd < in.txt / <<'EOF' / <<< "str"Read standard input from file / here-doc (quotation mark EOF means the content is not expanded) / here-string
a | b / a |& ba's stdout (/ plus stderr) is connected to b's stdin; both ends of the pipe are two processes running concurrently
a && b / a || b / a ; ba will be executed only if it succeeds b / a will be executed only if it fails b / unconditional sequential execution

The exit code of the pipeline defaults to the exit code of the last command; set -o pipefail causes the pipeline to fail when any link fails (Lesson 5 Script Engineering). ${PIPESTATUS[@]} can view the exit code of each segment.

Shell configuration files and variables

  • Login Shell (SSH login, sudo -i, bash -l): read /etc/profile (and /etc/profile.d/*.sh), and then The first one that exists among ~/.bash_profile, ~/.bash_login, and ~/.profile; Ubuntu's ~/.profile will then source ~/.bashrc.
  • Interactive non-login Shell (open another bash in the terminal): read /etc/bash.bashrc (Ubuntu) and ~/.bashrc. Non-interactive (script, cron): Read neither.
  • Shell variables vs environment variables: X=1 is only in the current Shell; it will be inherited by the child process (envp of execve) after export X=1. env looks at environment variables, set looks at all.
  • PATH: colon separated, search from left to right. Ubuntu adds ~/.local/bin and ~/bin (when present) to PATH by default. Never put . in PATH.

FHS: Where the files are placed

DirectoryResponsibilitiesMyapp used
/usr/bin, /usr/sbin, /usr/libPrograms and libraries installed by the distribution package (written only by the package manager). Both Ubuntu and RHEL have "usr merged": /bin → usr/bin, /lib → usr/lib is a symbolic link/usr/bin/python3, /usr/bin/redis-server
/usr/localThe local administrator manually compiles and installs the software (the package manager does not touch it)—
/optSelf-contained third-party/add-on applications, /opt//opt/myapp/app, /opt/myapp/venv
/etcNative configuration (text file), not the program/etc/myapp/myapp.env
/var/libPersistent state data of the program/var/lib/redis
/var/logJournald's persistent log in /var/log/journal)Lesson 2 Switch to journald
/var/cache, /var/tmpRebuildable cache; temporary file retained across reboots/var/cache/apt/archives
/tmpTemporary file, writable by everyone (sticky bit, module 3), probably tmpfs, cleared upon restart—
/runRuntime data (PID file, socket), tmpfs, rebuild at boot/run/redis
/srvService data provided by the local machine (site, FTP, share)Module 3 /srv/share
/home, /rootNormal user home directory, root's home directory/home/labadmin/linuxlab
/proc, /sys, /devVirtual file system exported by the kernel: process information, device and kernel parameters, device nodes/proc// (module 5)
/boot, /mnt, /mediaKernel and boot files; temporary mount points; removable mediaLesson 2 Mounting

When: What to pay attention to when using rust-coreutils in Ubuntu 26.04

26.04 ls, cat, chmod, sort, etc. come from uutils (rust-coreutils) and aim to be compatible with GNU behavior, but individual unpopular options, error message wording, and performance characteristics may be different. When encountering differences in script behavior: first use ls --version to confirm the implementation; the GNU version is provided with the gnu prefix (such as gnuls); you can also switch as a whole according to the Ubuntu documentation: sudo apt install coreutils-from-gnu coreutils-from-uutils- --allow-remove-essential (reverse switching reverses the two package names). Don't use update-alternatives to switch coreutils.

Common misunderstandings① “rm *.log It's rm looking for files" - it's bash expanded *, rm only receives a list of file names; file names starting with - will be treated as options and should be written as rm -- *.log or rm ./*.log. ② "Nothing is expanded in double quotes" - $VAR and $( ) in double quotes are still expanded, only splitting and wildcarding are prevented. ③ "cmd 2>&1 > f Equals cmd > f 2>&1" - redirection is executed from left to right, and the results are different in different orders. ④ "PATH is set in ~/.bashrc , which can also be seen by cron and systemd" - non-interactive environments do not read it. ⑤ "Things in /tmp will always be there" - it may be cleaned up during restart or by systemd-tmpfiles regularly.

FHS map: key directories on linuxlab

/ /usrbin sbin libPackage manager write /etcConfigurationmyapp/myapp.env /varlog lib cacheData that will grow /optmyapp/appmyapp/venv /homelabadmin/linuxlab/ /srvshare/External service data /tmpdrwxrwxrwtsticky /proc /sys/run /devKernel/runtime myapp’s files (comprehensive experiment) /opt/myapp/app/app.py root:myapp 0640 code (the application cannot change itself) /opt/myapp/venv/ root:root 0755 Python virtual environment /opt/myapp/run.sh root:myapp 0750 Start packaging script /etc/myapp/myapp.env root:myapp 0640 Configuration and Confidential /var/lib/redis/ redis:redis Redis data Log: This lesson → ~/linuxlab/myapp.log; Lesson 2 → journald Service: This lesson is run manually; Lesson 2 → /etc/systemd/system/myapp.service usr merge (both Ubuntu / RHEL have been completed) /bin → usr/bin /sbin → usr/sbin /lib → usr/lib /lib64 → usr/lib64 Who can write where: /usr is only written by apt / dnf (upgrade will cover manual changes) /etc administrator (dpkg will protect your modified conffile) /opt /srv /usr/local administrator or application installer /home each user · /tmp everyone (but can only delete their own)
Figure 2-1 Remember three sentences: the program is in /usr or /opt, the configuration is in /etc, and the changing data is in /var

File descriptors and redirections

Process grep fd 0 stdinfd 1 stdoutfd 2 stderr Output of previous commandPipe | or < file fd 0 > out.txt / | Next commandDefault: terminal 2> err.log / 2>&1Default: terminal (not entering the pipe)
Figure 2-2 The error message defaults to fd 2 and will not enter the pipe - so cmd | grep error Often "nothing is caught", write cmd 2>&1 | grep error

Shell expansion step-by-step demonstration

Select a command and see step by step how bash turns the text you enter into the parameter array (argv) passed to execve. Assume that the current directory ~/linuxlab/logs contains access.log, app 1.log (including spaces), error.log, HOME=/home/labadmin, f="app 1.log".

Expansion phase
Current results
 class="out" data-l="words" id="a2words" style="min-height:160px;white-space:pre-wrap"
Ready.
Verify it yourselfExecute set -x in bash and then run the command. Bash will print out the expanded results starting with + before execution; set +x Close. You can also use printf '[%s]\n' args… to view the boundaries of each parameter.

Command table

CommandFunctionKey points
pwd / cd - / cdCurrent directory / return to the previous directory / home directorypwd -P Display the physical path after parsing the symbolic link
ls -lah / tree -L 2Column directory (including hidden files, human-readable size)/treels -ld dir Look at the directory itself
cp -a / mv / rm -r / mkdir -pCopy (keep attributes)/move/recursively delete/recursively create directoryrm -ri Interactive confirmation; no recycle bin
ln -s target link nameSymbolic linkHard link ln cannot cross file systems and cannot link directories
cat / less / head -n / tail -fView filesless in / search, G to the end, q exit
findSearch by name, time, size, ownerfind /var/log -name '*.gz' -mtime +7 -size +1M
stat / fileinode metadata / file typestat -c '%A %U:%G %s %n' f
man / --help / helpManual / program help / bash built-in helpman 5 passwd Specify the chapter; man -k keyword
history / Ctrl+RHistory command/reverse search!! Previous article, sudo !! Use sudo to rerun
env / export / printenv PATHEnvironment variableVAR=x cmd only takes effect on this command
 data-l="bash"
 class="out" data-l="Expected Output"

How to verify: The result of wildcard expansion will not be split by words again, so app 1.log in demo/log/* is still a parameter; and the unquoted one $f will be torn down. Common mistakes: In the script, for f in $(ls) encounters an error in the file name with spaces. You should write for f in ./*.

 data-l="bash"
 class="out" data-l="Expected Output (Example)"

The error message of the second command is printed directly on the terminal (fd 2 still points to the terminal when 2>&1), without entering out2.txt.

 data-l="bash"
 class="out" data-l="Expected Output (Example, 26.04)"

Goal: Establish the experimental structure of ~/linuxlab and master expansion, redirection and PATH. Environment:linuxlab, labadmin. Fees: None.

Create a personal bin directory and add it to PATH:
 data-l="bash"
 class="out" data-l="Expected Output (Example)"

If there is no section in ~/.profile (for example, RHEL system), add export PATH="$HOME/.local/bin:$PATH" at the end of ~/.bashrc.

Inheritance of environment variables:
 data-l="bash"
 class="out" data-l="Expected Output"
Save errors and output separately and make statistics:
 data-l="bash"
 class="out" data-l="Expected Output (Example)"

These Permission denied are the permission checks discussed in module 3: labadmin does not have r or x permissions on these directories.

Take a tour of FHS:
 data-l="bash"
 class="out" data-l="Expected Output (Example)"

Whether /tmp is tmpfs depends on the distribution and version; when the file system of df -h /tmp is listed as tmpfs, it will be cleared after restarting.

Clean: rm -r ~/linuxlab/demo ~/linuxlab/out1.txt ~/linuxlab/out2.txt 2>/dev/null (retain tmp directory and PATH settings).

Case 1: An empty variable deleted the entire directory

Problem: Cleanup script rm -rf $BUILD_DIR/, one time BUILD_DIR was not set, and after expansion it became rm -rf / (modern rm default --preserve-root rejects the root directory, but the similar writing method rm -rf $DIR/* will delete everything that can be deleted under /*). Method: Use "${BUILD_DIR:?BUILD_DIR not set}". When the variable is empty, it will directly report an error and exit; add double quotes to all variables; start the script with set -u. Prevention: Running ShellCheck in CI (Lesson 5).

Case 2: The log "disappeared"

Problem: When the startup script is written app 2>&1 > /var/log/app.log, the error message is not entered into the log file, and there is no way to troubleshoot the failure. Method: Change to > /var/log/app.log 2>&1; a better approach is to leave it to systemd/journald for unified collection (Lesson 2).

Case 3: The files under /usr were manually modified and overwritten after the upgrade

Problem:Operation and maintenance directly modify /usr/lib/systemd/system/redis-server.service to adjust parameters, and all changes will be lost after the next apt upgrade. How to: The package manager owns /usr; native customizations should be placed in /etc (systemd uses systemctl edit to generate drop-ins, Lesson 2). Restrictions: dpkg only protects files registered as conffile under /etc. When upgrading, it will ask how to merge.

Common errors and solutions

rm: invalid option -- 'r' / Files whose file names start with - cannot be deleted

Reason: Wildcard expansion produces file names such as -rf.txt, which are treated as options by the program.

 data-l="bash"
bash: syntax error near unexpected token `(' / unexpected EOF while looking for matching `"'

Cause: The quotes are not paired, or bash syntax is used in sh (dash).

 data-l="bash"
-bash: /usr/bin/ls: Argument list too long

Cause: The total length of parameters expanded by wildcard expansion exceeds the kernel's ARG_MAX limit (execve returns E2BIG).

 data-l="bash"
Changed ~/.bashrc but it does not take effect in SSH login / cron / systemd

Reason: The login shell reads ~/.profile (in Ubuntu it reads ~/.bashrc again, but only when interacting); cron and systemd These files are not read at all.

 data-l="bash"

Fix: Place environment variables in the service's own configuration (systemd's Environment= / EnvironmentFile=, Lesson 2).

Command line operation questions
1. Create ~/linuxlab/proj/{src,test,docs} at once, and create README.md in each subdirectory.
 data-l="bash"
2. Run find / -name sshd_config, keeping only normal results and discarding all errors.
 data-l="bash"
Scenario analysis question
The deployment script contains cp $SRC/*.conf $DEST. The file was copied to the wrong location on one machine, and another machine reported "cp: target 'x' is not a directory". What could be the reason? How to change it?

Unquoted variables will be split by words: if DEST contains spaces (such as /srv/my app), it will be split into two parameters, and the last parameter will be regarded as the target; when SRC is empty, the glob will become /*.conf, copied from the root directory. Fix: cp -- "${SRC:?}"/*.conf "${DEST:?}/"; use [ -d "$DEST" ] to precheck; enable set -euo pipefail and ShellCheck.

Verified teaching video

▶
Linux Directories Explained in 100 Seconds — Fireship
English · Quick introduction to each directory of FHS
▶
Linux File System/Structure Explained! — DorianDotSlash
English · Explain the file system structure one by one directory
▶
Linux Crash Course: Navigating the Linux Filesystem — Learn Linux TV
English · Practical operation of cd, ls, relative/absolute paths
▶
Beginner's Guide to the Bash Terminal — Joe Collins (EzeeLinux)
English · Bash terminal introduction

Official documentation

Video storyboard script (about 75 seconds)

This courseware cannot directly generate videos/MP3s. Storyboards and explanation scripts have been provided, which can be generated by video tools.

Shot 1 · 0–20s
Screen: Input rm $f, $f becomes "app 1.log", and then is cut by scissors into two cards: "app" and "1.log".
Narration: Variables without quotation marks will be split, and rm receives two file names.
Shot 2 · 20–45s
Screen: Six gates light up in sequence: braces, tildes, variables, splits, wildcards, and dequotes.
Narration: bash is expanded in a fixed order before execution, and what is finally passed to the program is just a set of strings.
Shot 3 · 45–75s
Screen: The root directory tree is expanded, /etc, /var, /opt, /usr are highlighted in sequence, and the myapp file appears next to it.
Narration: The program is in usr or opt, the configuration is in etc, and the changing data is in var. This is FHS.
Or score ≥ 70% on the Quiz

Module 3 · Files, permissions, ownership and ACLs

13:00 – 21:00 · Every open / execve, the kernel has to answer a question: "Can this process do this to this inode?"
8 minutesacl(5) · path_resolution(7)Core Animation 2★★★★★
Learning Objectives
  • Understand each column of ls -l: file type, 9 permission bits, special bits, + (ACL), number of links, owner, group.
  • Explain the different meanings of r / w / x to file and directory (x of directory = can be entered/traversed, w = can be created, deleted and renamed).
  • Use chmod (symbol and octal), chown, chgrp, umask to set permissions; understand the roles and risks of SUID, SGID, and sticky.
  • Use setfacl/getfacl to authorize a single user or group, set the default ACL, and understand how mask limits effective permissions.
  • Deduce the result of an access according to the real algorithm of the kernel: capabilities → owner → named user → group → others (core animation 2 of this lesson).
Prerequisite knowledge:Modules 1 and 2. Importance:★★★★★ ("Permission denied" is the most common error you get on Linux)

What: ls -l of each column

 class="out" data-l="ls -l interpretation"
bitsFor filesFor directories
r(4)Read contentList the file names in the directory (ls)
w(2)Modify the content (deleting files looks at directory w) Create, delete, and rename entries in the directory (x is also required)
x(1)Execute as a programEnter/traverse the directory (cd, prerequisite for accessing files in it)
SUID (4000, s is in owner x position)The effective UID of the process becomes the file owner during execution (such as /usr/bin/passwd)Not meaningful on Linux
SGID (2000, s is in the x position of the group)The effective GID during execution becomes the file's groupThe group of the new file inheritance directory (required for shared directories)
sticky (1000, t is in the other x positions)meaninglessOnly the file owner, directory owner or root can delete/rename the file (/tmp is 1777)

Uppercase S/T means that the special bit is set but the corresponding x bit is not set. The kernel ignores SUID/SGID on scripts (#!) for security reasons.

Why: Where does the permission check occur

Permissions are not checked by ls or bash, but by the kernel at the system call entry (openat, execve, unlinkat, mkdirat...). Check the using process's file system UID (fsuid, usually equal to the effective UID), effective GID, and additional groups, plus the process's capabilities. The LSM (AppArmor for Ubuntu, SELinux for RHEL) can then deny it again (Lesson 6).

How: Kernel decision algorithm (acl(5), path_resolution(7))

  1. Path resolution: Search step by step starting from /, each directory passed requires x (search) permission, otherwise EACCES is returned - even if the target file itself is 777.
  2. capabilities: CAP_DAC_OVERRIDE bypasses read and write execution checks (but execution requires the file to have at least an x ​​bit); CAP_DAC_READ_SEARCH only bypasses read and directory searches. root has all capabilities by default.
  3. Owner: The effective UID is equal to the file owner → only look at the owner bit (user::), the match is final, and no longer look at the group and others.
  4. Named user ACL (user:bob:rw-): UID matching → The entry is determined after intersection with mask.
  5. Group: Valid GID or any additional group matching file belongs to the group (group::) or named group entry (group:ops:r--) → any matching entry (after intersection with mask) contains the required permissions and is allowed, otherwise rejected and will not look at other again.
  6. Other (other::): Used when none of the above match.

When there is no extended ACL, step 4 does not exist and mask does not participate. It is the classic "owner → group → other, the first match is the final result".

umask: default permissions for new files

The program requests a mode when creating the file (usually 0666 for the file, 0777 for the directory), and the kernel then removes the bits in the umask: 0666 & ~0022 = 0644, 0777 & ~0022 = 0755. umask only removes permissions, never adds x. UMASK 022 in Ubuntu's /etc/login.defs, combined with USERGROUPS_ENAB yes and pam_umask, will relax the group bit to be consistent with the owner (the common result is 0002) for ordinary users whose "username has the same name as the main group and UID=GID"; root is 0022. Subject to the actual output of the umask command. The Default ACL on the directory overrides the group/other parts of the umask.

When: Which mechanism to choose

RequirementsRecommended practices
A team shared directoryBuild a group + directory 2770 (SGID) + members join the group; add default ACL or adjust umask when new file group is required to be writable
Give "an additional person/group" read-onlyACL: setfacl -m u:bob:rX, instead of putting other Open
Multiple people can write but cannot delete other people's filessticky bit (chmod +t)
The program needs to bind <1024 port or capture packetscapabilities (setcap cap_net_bind_service=+ep, or systemd's AmbientCapabilities=, Lesson 2) instead of SUID root
Secret configuration of the serviceroot:myapp 0640: Root can be changed, the service is read-only and not visible to others
Common misunderstandings① "It doesn't matter if the owner has less permissions than the other, since the other has it anyway" - the conclusion is that the owner matches, but the owner himself cannot read it.chmod 0077 f ② "chmod 777 can solve the problem" - it just hides the problem and creates security holes; first use namei -l to find out which level lacks permissions. ③ "Deleting files requires the w permission of the file" - what is required is w+x of the directory is located (and the owner if sticky). ④ "If rw is given to setfacl, it will definitely be able to write" - it also depends on the mask; later execution where chmod g-w will change the mask together. ⑤ "It will take effect immediately after joining the group" - the group list is determined when logging in. If there is an existing session, you need to log in again or newgrp(module 4).

Permission determination flow chart

System call openat("/srv/share/report.txt", O_RDWR)Process: fsuid, egid, additional group, capabilities ① Each directory on the path has x? No data-xlt-id="T18">③ fsuid == owner? / → /srv → /srv/share No EACCES ② CAP_DAC_OVERRIDE?root has it by default Yes Allow(requires at least 1 x bit for execution) ③ fsuid == owner? → See only the user:: bit (conclusion) Yes user:: contains the required bit? Yes→Allow No→Deny ④ Named user ACL user:UID? Item ∧ mask (conclusion) Yes (Item ∧ mask) Contains? Yes → Allow No → Deny ⑤ Any group matches group:: / group:G? Any matching entry ∧ mask contains the required bits? Match Yes→AllowNone→Reject (do not look at other) ⑥ other:: Contains the required bits? Yes→Allow No→EACCES And later · LSM: AppArmor/SELinux (Lesson 6) · Mount options: ro, noexec, nosuid · File attributes: chattr +i / +a Difference in error reports: EACCES Permission denied(DAC/LSM) EPERM Operation not permitted EROFS Read-only file system
Figure 3-1 From top to bottom, the first "matching" category gives the conclusion; only when there is a complete mismatch, it will fall to the next category

Design of shared directory /srv/share

/srv/share drwxrws---+ root devs 2770: SGID → The new file group is automatically devs ACL: user:bob:r-x group:ops:r-x Default ACL: default:group::rw- default:user:bob:r-- → The new file is writable to the devs group and read-only to bob other: --- nothing can be seen report.txt -rw-rw----+ alice devs user::rw- alice (owner) user:bob:r-- bob read-only (from default ACL) group::rw- carol and other devs members can write mask::rw- ← ls The middle three digits show it other::--- eve, myapp has no permission
Figure 3-2 SGID solves "Who is the group to belong to", and the default ACL solves "What permissions are given to whom in the new file"

Core Animation 2: Permission determination

Object: Directory /srv/share (root:devs 2770, ACL user:bob:r-x, group:ops:r-x) and file report.txt (alice:devs, ACL user::rw-, user:bob:rw-, group::r--, group:ops:r--, mask::r--, other::---). Choose "who" and "what" and decide step by step in the order of the core.

Judgment steps
getfacl report.txt (current)
 class="out" data-l="acl" id="a3acl" style="min-height:170px;white-space:pre-wrap"
Ready.

chmod / umask calculator

rwxSpecial bit
user
group
other
 class="out" data-l="Results" id="a3calcout"

Command list

CommandFunctionExample
chmodChange permissions (symbol or octal)chmod u+x,go-w f, chmod 640 f, chmod -R g+rX dir (big X: only add x to directories and files that already have x)
chown / chgrpChange the owner/group (root is required to change the owner)sudo chown -R myapp:myapp /var/lib/myapp
umaskView/set the umask of the current shellumask -S symbol display
getfacl / setfaclView/set the ACLsetfacl -m u:bob:rX f, -x delete entry, -b delete all, -d default ACL, -R recursive
namei -l pathDisplay the permissions of each component on the path step by stepFind "Which level is missing x"
statOctal mode, inode, timestampstat -c '%a %A %U:%G %n' f
getcap / setcapFile capabilitiesgetcap -r /usr/bin 2>/dev/null
lsattr / chattrFile system attributes (immutable i. Append only a) sudo chattr +i /etc/resolv.conf (use with caution)
find -permFind by permissionssudo find / -xdev -perm -4000 -type f List SUID File
 data-l="bash"
 class="out" data-l="Expected output (example, Ubuntu regular user)"

How to verify: When the umask is 0002, the new file is 664 and the directory is 775; when it is 0022, it is 644 / 755. The s of /usr/bin/passwd allows ordinary users to modify the own line in /etc/shadow as root (the passwd program does an identity check internally). Common mistakes:chmod -R 755 adds x to all files.

 data-l="bash"
 class="out" data-l="Expected output (example)"

systemd uses ACLs to allow members of the adm group (the first user created during Ubuntu installation) to read the journal without sudo - ACLs can be found everywhere in distributions. The specific entries are subject to your system.

Goal: Create a shared directory /srv/share: devs group is read-write, bob is read-only, and others are not visible; verify SGID, default ACL, mask and sticky. Environment:linuxlab, labadmin (requires sudo). Users alice, bob, carol and group devs will be discussed in detail in module 4. Let’s quickly create them here. Fees: None.

Prepare users and groups:
 data-l="bash"
 class="out" data-l="Expected output (example)"
Create a shared directory:
 data-l="bash"
 class="out" data-l="Expected output (example)"

The capital X in rX takes effect as x for the directory. default:user:: not specified in the default ACL is copied from the access ACL, default:mask:: is automatically calculated by setfacl as the union of group class entries (rw- ∪ r-- = rw-). labadmin is not in the devs group and is not the owner, so ordinary getfacl will fail due to the lack of x and requires sudo - this is a permission determination in itself.

Authenticate with different identities:
 data-l="bash"
 class="out" data-l="Expected output (example)"

Although alice's umask is 0022, the new file is still group-writable: when the directory has a default ACL, the umask does not participate, and the group permissions come from the default ACL. The owned group is devs instead of alice's primary group. This is the effect of SGID.

Observe the role of mask:
 data-l="bash"
 class="out" data-l="Expected Output (Example)"
sticky and SUID inspection:
 data-l="bash"
 class="out" data-l="Expected Output (Example)"

Uppercase T: sticky is set but other has no x. The list of SUID files should be regularly compared to the baseline, and the presence of unfamiliar files is a sign of an intrusion (Lesson 6). sudo itself is also SUID root (sudo-rs on 26.04).

Cleanup: Keep /srv/share, alice/bob/carol/eve and devs, module 4 continues to be used.

Case 1: SSH key login suddenly fails

Problem: After someone executes chmod -R 775 /home/deploy, the deploy user cannot log in with the key, and the log Authentication refused: bad ownership or modes for directory /home/deploy. Root cause: sshd's StrictModes requires that the home directory, ~/.ssh, and authorized_keys cannot be written by others. How to:chmod 755 ~ ; chmod 700 ~/.ssh ; chmod 600 ~/.ssh/authorized_keys (Lecture 2 SSH module is explained in detail).

Case 2: Web service 403, chmod 777 is useless

Problem:nginx reads /home/alice/site/index.html and returns 403. The team changed the file to 777 but it still doesn't work. Root cause: The path /home/alice is 750, and the nginx process user (www-data) cannot traverse without x. Method: Do not put the site in the home directory, move it to /srv/www; or use minimum authorization setfacl -m u:www-data:x /home/alice. Tools:sudo -u www-data namei -l /home/alice/site/index.html.

Case 3: Confidential file read by everyone

Issue: Security scan found /etc/myapp/myapp.env permission 644, containing Redis password. How to:root:myapp 0640; Directory /etc/myapp is 0750 root:myapp; Pin these permissions in Configuration Management (Lesson 5 / Ansible Lesson). Prevention: Check find /etc -perm -o+r -name '*.env' during readiness review.

Common errors and solutions

Permission denied (file permissions appear to be OK)

Troubleshooting order:① x at each level on the path; ② Who am I (id, whether the group has taken effect); ③ ACL and mask; ④ mount options; ⑤ AppArmor / SELinux.

 data-l="bash"
rm: cannot remove 'x': Operation not permitted (sudo does not work either)

Reason: The file has immutable attribute i or only appends a; or it is located in the sticky directory and you are not the owner (when not root).

 data-l="bash"
setfacl: Operation not supported

Cause: The file system does not support ACL (such as some network or FAT file systems, WSL's /mnt/c). ext4/xfs/btrfs are supported by default.

 data-l="bash"
chown: changing ownership of 'x': Operation not permitted

Reason: Only the process (root) that owns CAP_CHOWN can modify the owner; ordinary users can only chgrp their own files to the group to which they belong.

 data-l="bash"
Command line operation questions
1. Let the directory /srv/reports belong to the group devs, the group can read and write, new files automatically belong to devs, others have no permission, and let the group ops read-only (including new files in the future).
 data-l="bash"
2. Find ordinary files under /etc that others can write to.
 data-l="bash"
Scenario Analysis Question
File -rw----r-- 1 alice devs app.conf: Can alice read it? Can carol (devs member) read it? Can eve (other people) read it? Why?

alice can read (owner bit rw-). carol cannot read: She matches the group devs, and the group position is ---. The judgment ends at the group level and will not fall back to other. eve can read (other bit r--). This shows that Unix permissions are not "take the maximum value", but "the first matching category wins".

Verified teaching video

▶
Linux Crash Course - Understanding File & Directory Permissions — Learn Linux TV
English · rwx, octal, chmod / chown practice
▶
Linux Crash Course | User Permissions - Access Control Lists (ACL) — The Technology Sandbox
English · setfacl / getfacl and mask
▶
Linux Crash Course | File System - Permission — The Technology Sandbox
English · Basics of file system permissions

Official document

Video storyboard script (about 90 seconds)

This courseware cannot directly generate video/MP3. Storyboards and explanation scripts have been provided, which can be generated by video tools.

Shot 1 · 0–20s
Screen:-rw-r-----+ is split into five sections, each section is highlighted and its meaning is marked.
Narration: The first one is the type, and then the three groups of rwx are for the owner, the group, and others respectively. The plus sign indicates that there is also ACL.
Shot 2 · 20–50s
Screen: A process card "bob" starts from the door and passes through the three doors /, /srv, /srv/share in sequence, and checks x at each door.
Narration: Each level of directory on the path must have execution permission. If this step fails, there is no need to look at the following ones.
Shot 3 · 50–75s
Screen: Determination ladder: root? Owner? Named user? Group? other? bob stops at "named user" and his rw intersects with mask r leaving only r.
Narration: The first matching category gives the conclusion; entries naming users and groups also intersect with the mask.
Shot 4 · 75–90s
Screen: A new file is born, 0666 minus umask 0022 becomes 0644; the SGID directory next to it makes the group become devs.
Narration: umask determines the default permissions for new files, and SGID makes files in the shared directory belong to the team.
Or score ≥ 70% on the Quiz

Module 4 · Users, groups and sudo

21:00 – 28:00 · The kernel only recognizes numeric UID/GID; names, passwords, group members and "who can be root" are all written in /etc Several text files
7 minutes26.04: sudo-rsAlways use visudo★★★★★
Learning objectives
  • Read Fields of /etc/passwd, /etc/shadow, and /etc/group; distinguish ordinary users, system users (service accounts) and root.
  • Use useradd / adduser, usermod -aG, passwd, chage, userdel to manage user life cycle; know when group membership changes take effect.
  • Write secure sudo rules (/etc/sudoers.d/ + visudo), understand %sudo / %wheel, NOPASSWD, command whitelist, secure_path and logs.
  • Learn about the differences between Ubuntu 26.04's default sudo-rs and traditional sudo (sudo.ws), and how to switch.
Prerequisite knowledge:Module 3. Importance:★★★★★

What: Account Database

FileFormat (colon separated)Permissions
/etc/passwdname:x:UID:GID:GECOS:home:shell, x means the password is in shadow644 root:root (readable by everyone)
/etc/shadowname:hash:last modified:min:max:warning:grace:expiry:; hash in $y$ (yescrypt) or Starting with $6$ (SHA-512); ! or * means locked/unavailable password login640 root:shadow(Ubuntu)/ 000(RHEL)
/etc/groupgroup:x:GID: member 1, member 2 (only additional members are listed here, the main group is in the GID field of passwd)644
/etc/login.defsUID/GID range, umask, password validity period default value644
TypeUID range (Ubuntu / RHEL default)FeaturesExample
root0Has full capabilities; prohibiting direct SSH logins is a common baselineroot
System user1–999(SYS_UID_MIN–SYS_UID_MAX)Run services, no password, usually no login Shell (/usr/sbin/nologin)redis, sshd, myapp
Normal user≥ 1000(UID_MIN)Human account, with home directory and Shelllabadmin, alice

Other sources: Users may also come from LDAP / Entra ID / SSSD (Lesson 3 Entra ID login). getent passwd alice will query all sources through NSS, which is more reliable than grep /etc/passwd.

Why: Why do services need dedicated system users

  • Minimum permissions: When myapp is compromised, the attacker only gets the permissions of the myapp user and cannot read /etc/shadow or change the code in /opt/myapp/app (the owner is root).
  • Auditable: ps -u myapp, ss -ltnp, and the UID in the log can directly correspond to the service.
  • Cannot log in: The shell is nologin, the password field is !, and cannot be entered through SSH or su (root can still sudo -u myapp).

How: Workflow for sudo

  1. /usr/bin/sudo is SUID root Program: labadmin When you execute it, the effective UID of the process becomes 0 (special bit for module 3).
  2. Read the files in /etc/sudoers and @includedir /etc/sudoers.d, and match the rules according to the "user/group host=(target user:target group) command". The last matching rule takes effect.
  3. Verify the caller's own password (not the root password) through PAM when necessary. After success, write the timestamp. By default, the same terminal will not ask again within 15 minutes.
  4. Record logs (syslog/journald: who, in which terminal, in whose identity, what was executed).
  5. Reset the environment (env_reset), set PATH to secure_path, switch to the target user's UID/GID/attachment group, then execve the target command; the exit code is returned unchanged.

sudoers rule syntax

 class="out" data-l="sudoers example"
  • The command must write an absolute path; if parameters are written, only these parameters are allowed. If no parameters are written, any parameters are allowed.
  • Dangerous whitelist: vi, less, find, tar, python, bash, systemctl edit, apt install, etc. can "escape" into root shell - giving them is equivalent to giving ALL.
  • File names in /etc/sudoers.d/ containing . or ending with ~ will be ignored (sudoers(5)), so use 90-devs instead of devs.conf; the permissions should be 0440.

Differences between sudo-rs (Ubuntu 26.04 default) and traditional sudo

Aspectssudo.ws (24.04 default)sudo-rs (26.04 Default)
ImplementationC, with a long history and comprehensive functionsRust rewritten, aiming for memory safety and simplicity
Password prompt[sudo] password for labadmin:[sudo: authenticate] Password: (per PAM prompt) - expect scripts matching old prompts will timeout
I/O logs and sudoreplaySupportedNot supported (sudo_logsrvd etc. are not provided)
LDAP sudoerssudo-ldapNot supported, use PAM/SSSD instead
sudoers syntaxCompleteSupports common subsets; use man sudoers-rs to view supported settings, sudo - help The name can still be called directly
Switchsudo update-alternatives --config sudo (interactive) or sudo update-alternatives --set sudo /usr/bin/sudo.ws; the original version can still be called directly with the name of sudo.ws

When: su, sudo, sudo -i how to choose

CommandWhose password is neededEnvironmentSuggestion
sudo cmdOwnReset, PATH=secure_pathPreferred: single command, leaving audit records
sudo -iOwnSimulate root login ShellWhen multiple consecutive root operations are required
sudo -u myapp cmdYour ownAs myapp identityVerify the permissions of the service account (used extensively in this lesson)
su -root of(Ubuntu default root has no password → not available)Root login ShellNot recommended: shared root password cannot be traced back to people
Common misunderstandings① “usermod -G devs alice Add alice to devs" - without -a , her additional group will be replaced with only devs, which may kick the administrator out of the sudo group. ② "Joining the group takes effect immediately" - the group list is determined by initgroups when logging in. Existing sessions need to be logged in again (or newgrp devs open a new Shell) ③ "It's okay to directly vim /etc/sudoers" - syntax errors will invalidate all sudo; visudo will be checked before saving ④. "NOPASSWD is just a convenience" - it allows anyone who gets the user's session (or a malicious script) to become root directly. ⑤ "Just delete the user" - to deal with the home directory, cron, files belonging to the UID (find / -uid) and SSH keys.

What a user looks like in each file

/etc/passwd alice:x:1002:1003:Alice Ops:/home/alice:/bin/bash myapp:x:998:998::/opt/myapp:/usr/sbin/nologin /etc/shadow(root:shadow 640) alice:$y$j9T$...:20409:0:99999:7::: myapp:!:20409::::: (! = cannot log in with password) /etc/group sudo:x:27:labadmin devs:x:1002:alice,carol alice:x:1003: myapp:x:998: The kernel only sees numbers: process credentials = ruid/euid/suid/fsuid + rgid/egid + Additional group list (read by initgroups from /etc/group at login)
20409 in Figure 4-1 shadow is "number of days since 1970-01-01" (example value);chage -l will be converted to date

sudo authorization path

labadminuid 1001 sudoSUID → euid 0 sudoers+ sudoers.d/* PAM authenticationOwn password Logjournald Switch identityenv_reset execveuid 0 Rule mismatch → deny and log; authentication failed 3 times → exit Note: Redirect > Executed by your shell before sudo (module 1)
Figure 4-2 sudo verifies "who you are" and "whether the rules allow it", not "do you know root" Password"

sudo authorization process

Select a scenario and gradually observe how sudo matches rules, authentication, recording and execution. Rules: %sudo ALL=(ALL:ALL) ALL (Ubuntu default) added experimentally with this module /etc/sudoers.d/90-devs: %devs ALL=(root) NOPASSWD: /usr/bin/systemctl restart ssh.service, /usr/bin/systemctl status ssh.service.

Ready.
The real mechanism corresponding to the animationsudo relies on the SUID bit to obtain euid 0 to read /etc/sudoers (permissions 0440 root:root) and switch identities; authentication through PAM sudo Service configuration (/etc/pam.d/sudo) is completed; finally use setresuid/setresgid/setgroups to switch to the target identity execve. The wording of the rejection message is different between sudo.ws and sudo-rs (marked in the animation). When troubleshooting, refer to the log.

Command table

CommandFunctionKey points
id [user] / groups / whoamiView identity and groupid Display the group of current process, id alice Display group in database
getent passwd|group|shadow nameQuery account via NSSContains LDAP / SSSD users
useradd -m -s /bin/bash uCreate user (underlying tool, common to all distributions)-r system user, -d home directory, -M do not create a home directory, -G additional group
adduser uDebian/Ubuntu The interactive package (link to useradd on RHEL)will prompt to set password and GECOS
usermod -aG g uAppend additional groupBe sure to bring -a; -L/-U Lock/unlock, -s Change Shell, -e Expiration date
gpasswd -d u gRemove user from groupAlso deluser u g (Ubuntu)
passwd / chageSet password / Password validity periodpasswd -S u status, chage -l u, chage -d 0 u Force password change at next login
userdel -r uDelete user, home directory and mailFirst pkill -u u; after find / -xdev -nouser
visudo / visudo -f file / visudo -cSafe editing/inspection sudoersEDITOR=nano sudo visudo -f /etc/sudoers.d/90-devs
sudo -l / sudo -l -U uList your own/a user's sudo permissionsThe first step in troubleshooting
sudo -k / sudo -vClear/refresh the authentication timestampFirst -k
last / lastlog / who / wLogin record and current sessionlastlog has been replaced by lastlog2 on some systems
 data-l="bash"
 class="out" data-l="Expected output (example)"

The output format of sudo -l is slightly different between sudo-rs and sudo.ws. The hash prefix $y$ means yescrypt (the default algorithm on Ubuntu and EL10).

 data-l="bash"
 class="out" data-l="Expected output (example, 26.04)"

The installation path and version number of sudo-rs are taken as an example, based on the output of readlink and --version on your system; on 24.04, readlink outputs /usr/bin/sudo, and the version is "Sudo version 1.9.x".

Goal: Complete the user life cycle: create dave (ops group), grant restricted sudo to the devs group, lock and delete eve; verify the effective timing of group membership. Environment:linuxlab, labadmin; alice/bob/carol/eve/devs created by module 3. Fees: None.

Create group ops and user dave, set password policy:
 data-l="bash"
 class="out" data-l="Expected output (example)"
Give devs group restricted sudo (edit drop-in with visudo):
 data-l="bash"

Write the following content and save:

 data-l="sudoers"
 data-l="bash"
 class="out" data-l="Expected output (example)"

If visudo is not on your system (depending on the sudo provider), first confirm with command -v visudo; do not fall back to direct editing.

Authentication whitelist:
 data-l="bash"
 class="out" data-l="Expected output (example)"

-n (non-interactive) allows sudo to fail directly when a password is required instead of prompting - suitable for scripts and testing. Commands that are not in the whitelist have no NOPASSWD rule to match, so the password is required first (and will be rejected once entered). The error wording depends on your sudo implementation.

When does group membership take effect:
 data-l="bash"
 class="out" data-l="Expected output (example)"
Lock, audit and delete eve:
 data-l="bash"
 class="out" data-l="Expected output (example)"

Only passwd -l locking the password does not prevent SSH key login; also set expiration (-e 1) or change the shell to nologin Only reliable.

Cleaning: Keep alice/bob/carol/dave, devs/ops and 90-devs (module 8 readiness review checks them).

Case 1: A usermod locked the administrator out

Problem: In order to allow the ops user to read the log, usermod -G adm ops was executed (missing -a), and ops was moved out of sudo group; there are no other administrator accounts at the time, and the rights cannot be escalated after the next login. How to: Restore via Cloud Serial Console/Single User Mode (Lessons 3, 4, 7). Prevention: Always -aG; retain at least two administrator identities; hand over accounts and groups to configuration management (Ansible lesson).

Case 2: less in the whitelist becomes root Shell

Problem: In order to allow the on-duty personnel to view the log, sudoers wrote NOPASSWD: /usr/bin/less /var/log/*; enter !bash in less to get root Shell, and wildcards also allow /var/log/../../etc/shadow. Method: Instead, add the on-duty personnel to the adm group to read the log directly (or systemd-journal group) without sudo. Principle: Do not use sudo if it can be solved with group permissions/ACL; when you must use sudo, only list specific commands and parameters that will not spawn a shell, or use sudoedit to edit files.

Case 3: The cron of the resigned employee is still running

Problem: After the account is deleted, its crontab is "resurrected" because the UID is reassigned to the new employee and runs as the new employee. How to: Offboarding process: Lock → Export data → crontab -r -u → userdel -r → find / -uid OLD Clean up legacy files; centralize identity (Entra ID / LDAP) to avoid UID reuse (Lesson 3).

Common errors and solutions

bob is not in the sudoers file. / I'm sorry bob. I'm afraid I can't do that

Cause: The user does not have any matching sudoers rules (the first sentence is the wording of sudo.ws, the second sentence is the wording example of sudo-rs), or has just joined the sudo group but has not logged in again.

 data-l="bash"

Fix: sudo usermod -aG sudo bob to let bob log in again; or add minimal rules in sudoers.d.

>>> /etc/sudoers.d/90-devs: syntax error near line 2 <<<

Reason: The rule syntax is incorrect (missing comma, the command does not write an absolute path, and there is a space after the line continuation character). visudo will ask "What now?": Press e to re-edit, don't choose to force save.

 data-l="bash"

If sudo is broken: Available on Ubuntu with pkexec visudo (requires polkit authentication), or via console/rescue mode fix.

The rules in sudoers.d do not take effect (visudo -c also passes)

Reason: The file name contains . (such as devs.conf) or ends with ~ end and is ignored; or is overridden by another rule (the last match takes effect).

 data-l="bash"
This account is currently not available.

Cause: The user's shell is /usr/sbin/nologin (normal configuration for system users).

 data-l="bash"
Command line operation questions
1. Create system user backup: no home directory, no login, main group with the same name.
 data-l="bash"
2. List all common usernames with UID ≥ 1000 and their shells.
 data-l="bash"
Scenario analysis question
The development team hopes to "deploy myapp": copy the new code to /opt/myapp/app and restart the service. Please design your permission scheme to avoid giving them full root.

Proposal: ① Create the deployers group; ② Keep the code directory root:myapp, with a reviewed deployment script /usr/local/sbin/myapp-deploy that is owned by root and cannot be written by ordinary users to complete "verify package → copy → set permissions → restart"; ③ sudoers.d: %deployers ALL=(root) /usr/local/sbin/myapp-deploy (without NOPASSWD, or only for CI account NOPASSWD); ④ Escapeable commands such as cp, vi, systemctl edit are not granted; ⑤ Audit logs enter journald and are collected centrally. After using systemd in Lesson 2, you can add polkit rules to only allow myapp.service to be restarted. Take it one step further: Hand over to CI/CD (Jenkins / GitHub Actions class).

Verified teaching video

▶
Linux Crash Course - Managing Users — Learn Linux TV
English · useradd / usermod / userdel / passwd practice
▶
Linux Crash Course - sudo — Learn Linux TV
English · sudo and sudoers basics; recorded before sudo-rs became the default, the prompt wording shall be subject to this lesson

Official documentation

Video storyboard (about 75 seconds)

This courseware cannot directly generate videos/MP3s. Storyboards and explanation scripts have been provided, which can be generated by video tools.

Shot 1 · 0–20s
Screen: three cards passwd, shadow, group, Alice's row is highlighted on the three cards.
Narration: Usernames, password hashes, and group members live in three files respectively. The kernel only recognizes numeric UIDs and GIDs.
Shot 2 · 20–50s
Screen: labadmin knocks sudo, a shield marked with s turns him into euid 0, then open the sudoers rulebook and find the %sudo line.
Narration: sudo is a SUID program. It first checks the rules, then verifies it with your own password, and then records the log.
Lens 3 · 50–75s
Screen: less appears in the whitelist, enter !bash in less, the screen turns red and displays root#.
Narration: If the program in the whitelist can open Shell, it is equivalent to giving root. If it can be solved with groups and ACLs, don't use sudo.
Or score ≥ 70% on the Quiz

Module 5 · Processes, Signals and Job Control

28:00 – 35:00 · Process = running program + credentials + open files; signals are "short messages" sent by the kernel to the process
7 minutes/proc · signal(7)TERM first, then KILL★★★★★
Learning objectives
  • Tell the key attributes of the process (PID, PPID, UID, status, priority, open files) and how to view them in /proc/.
  • Interpret the process status R / S / D / T / Z / I, and know how zombie processes and orphan processes are generated and who recycles them.
  • Master the default actions of common signals (HUP, INT, QUIT, KILL, TERM, STOP, TSTP, CONT, CHLD) and be able to use kill, pkill, trap to stop the process correctly.
  • Use job control: &, Ctrl+Z, jobs, fg, bg, disown, nohup, and know why production services should be left to systemd (Lesson 2).
Prerequisite knowledge: Fork / execve / wait of module 1. Importance:★★★★★

What: What does the process have

AttributesMeaningWhere to see
PID / PPIDProcess number / Parent process number; PID 1 is systemdps -o pid,ppid, pstree -p
CredentialsReal/valid/saved/filesystem UID and GID, additional groups, capabilitiesUid, Gid, Groups, Cap* of /proc/PID/status Row
StatusR running or ready, S interruptible sleep (waiting for events), D non-interruptible sleep (usually waiting for disk/NFS I/O), T stopped, Z zombie, I idle kernel threadps -o stat, suffix + Foreground process group, s session first process, l multi-threading, </N high/low priority
File descriptorOpened files, pipes, socketsls -l /proc/PID/fd, lsof -p PID
Environment and command lineexecve incoming argv / envp/proc/PID/cmdline, /proc/PID/environ (separated by \0, only owner/root Readable)
ResourcesCPU time, memory (RSS / VSZ), nice value, limit (ulimit), cgrouptop, /proc/PID/limits, /proc/PID/cgroup

Signal (signal(7), x86-64 number)

SignalNumberDefault actionTypical sources and uses
SIGHUP1TerminationTerminal disconnected; many daemon processes agree to "reload configuration"
SIGINT2TerminationCtrl+C (sent to the foreground process group)
SIGQUIT3Terminate and core dumpCtrl+\
SIGKILL9Terminate (cannot be captured, cannot be ignored)kill -9, OOM Killer; the process has no time to clean up
SIGTERM15Terminate (can be captured)kill's default signal; first sent when systemd stops the service; graceful exit
SIGCHLD17ignorechild process status change, the parent process should wait
SIGCONT18continuefg / bg
SIGSTOP19Stop (cannot capture)kill -STOP
SIGTSTP20Stop (can capture)Ctrl+Z
SIGSEGV / SIGPIPE11 / 13Terminate (SEGV and core)Illegal memory access/write to closed pipe (yes | head in yes)

The signal number is related to the architecture. Please write the name (kill -TERM) instead of the number in the script. For a process terminated by signal N, $? in Shell is 128+N (TERM → 143, KILL → 137, INT → 130).

Why: "TERM first and then KILL"

SIGTERM gives the program a chance to complete the request being processed, refresh the buffer, delete the lock file and temporary file, and notify the child process (gunicorn will gracefully stop the worker when receiving TERM). SIGKILL terminates the process directly by the kernel, possibly leaving behind corrupted data, stale PID/lock files, and half-written files. Correct process: kill -TERM → Wait (systemd default is 90 seconds, TimeoutStopSec) → Still do not exit and then kill -KILL. For a process in D state, even SIGKILL must wait for I/O to return before it takes effect.

How: Job Control and Session

  • Each terminal is a session, and bash is the first process of the session; each pipeline is a process group (job), and only one job is in the foreground, which can read the terminal and receive Ctrl+C / Ctrl+Z.
  • cmd & starts the job in the background; Ctrl+Z sends SIGTSTP to stop the foreground job (T); bg %1 sends SIGCONT to let it continue in the background; fg %1 brings it back to the foreground and continues.
  • When the terminal is closed, the kernel sends SIGHUP to the session, and bash forwards the SIGHUP to its job → the background task exits. nohup cmd & makes cmd ignore SIGHUP and write output to nohup.out; disown makes bash not forward; setsid makes it enter a new session.
  • After the parent process exits, the child process becomes orphan, adopted by PID 1 (systemd, or a process with subreaper set, such as systemd --user) and recycled after its exit. The child process has exited but the parent process still wait, leaving zombie (Z, which only occupies one process table entry and does not occupy memory; killing the zombie is ineffective and its parent process needs to be processed).

When: run manually vs leave it to systemd

MethodApplicableDisadvantages
Foreground / & / Ctrl+ZInteractive debugging, temporary tasks (manually run myapp in this lesson)Stop when the terminal is closed
nohup / tmux / screenLong tasks (data migration) that need to span SSH disconnectionsNo automatic restart, log management, resource limit
systemd serviceAll production services (Lesson 2 turns myapp into myapp.service)Need to write unit files
Common misunderstandings① "Kill means killing the process" -kill It just sends a signal, the default is TERM, and the program can choose to process or ignore it. ② "Kill -9 is the most reliable" - it skips cleanup and is ineffective against D state and zombies; should be used as a last resort. ③ "The zombie process occupies memory, you need to kill -9 it" - the zombie is already dead, killing it is useless, you have to ask the parent process to wait or restart the parent process. ④ "Load average is CPU usage" - Linux load includes the number of tasks in R and D status, and I/O stuck will also increase the load (Lesson 7). ⑤ "Just add an & for background operation" - SIGHUP will be received when SSH is disconnected; production services are handed over to systemd.

Process State Machine

fork + execveNew Process R Running/ReadyOn CPU or queued S Interruptible SleepWait for network/timer/input D Uninterruptible sleepWait for disk/NFS T StopSIGSTOP / SIGTSTP TSTPCONT Z zombieExitedWaiting for the parent process wait exit / signal Recyclingwait4 The parent process exits first → the orphan is adopted by PID 1 systemd is responsible for recycling them
Figure 5-1 Switching between R and S thousands of times per second; T is generated by job control or debugger; Z only exists at the moment of "exited but not recycled"

The destination of sessions, process groups and signals

Session (SID = bash's PID) · Control terminal /dev/pts/0 bashSession first processjobs / fg / bgWhen the terminal is closedForward SIGHUP Foreground job [2] (a process group)grep 500 access.log | sort | uniq -cCtrl+C → SIGINT is sent to the entire process groupCtrl+Z → SIGTSTP Background job [1]sleep 300 & (status S, without +)Read terminal → stop after receiving SIGTTINnohup / disown / setsid can be detached
Figure 5-2 Keyboard signals are only sent to the foreground process group; background jobs are not affected by Ctrl+C, but will be affected by SIGHUP when the terminal is closed. Impact

Process State Machine: Signal the process yourself

Start python3 -m http.server 8000 (a long-running program that can capture SIGTERM) in a simulated terminal, and then use buttons to perform job control and signal operations. The current status of the process is highlighted in the figure, and the actual command and the output of ps -o pid,ppid,stat,cmd / jobs are shown below. Illegal operations will be rejected and reasons given.

Not running$ prompt Foreground S+Occupy terminal Stop T[1]+ Stopped Backend S[1]+ Running Z zombieWait Recycled$? = —
Click "Start" to start.
labadmin@linuxlab:~/linuxlab$
The real mechanism corresponding to the animationCtrl+Z / Ctrl+C is sent by the terminal driver (tty line procedure) SIGTSTP / SIGINT toForeground process group; fg/bg By The bash call tcsetpgrp switches the foreground process group and sends SIGCONT; after the child process exits, the kernel turns it into a zombie and sends SIGCHLD to bash, and the bash call waitpid recycles and prints [1]+ Done or Terminated . Python's http.server throws KeyboardInterrupt for SIGINT and exits (status 130); it uses the default action for SIGTERM and terminates directly (143).

Command table

CommandFunctionKey points
ps -ef / ps auxList all processes (System V / BSD style)ps -eo pid,ppid,user,stat,ni,%cpu,%mem,etime,cmd --sort=-%cpu | head
pstree -puProcess tree (with PID and user switching)From psmisc
top / htopLive viewtop in P/M sort by CPU/memory, k signal, 1 expand each CPU
pgrep -a / pkillFind or signal by name/user/full command linepgrep -u myapp -f gunicorn; confirm with pgrep first and then pkill
kill -SIG PID / kill -lSend/list signalskill -0 PID Only check if the process exists and has permissions
jobs -l / fg / bg / disownJob control%1, %+, %sleep
nohup cmd & / setsid cmdIgnore SIGHUP / New sessionOutput defaults to nohup.out
nice -n 10 cmd / reniceAdjust CPU priority (-20 is the highest, 19 is the lowest)Lowering the priority can be done by ordinary users, raising it requires root
trap 'cmd' TERM INTCapture signal in scripttrap - TERM Restore default; KILL/STOP cannot be captured
uptime / cat /proc/loadavgLoadComparison with nproc
 data-l="bash"
 class="out" data-l="Expected output (example, excerpt)"

-bash The dash in front represents the login shell; the four values in the Uid line are real, valid, saved, and file system UID. The process title format of sshd varies with the OpenSSH version.

 data-l="bash"
 class="out" data-l="Expected output"

yes Writing to the closed pipe after head exit, received SIGPIPE(13) → 128+13 = 141. This is common in pipes and is usually harmless.

Objective: Practice job control, compare SIGTERM and SIGKILL, observe zombies and orphans. Environment:linuxlab, labadmin. Fees: None.

Job Control:
 data-l="bash"
 class="out" data-l="Expected output (example)"

The process running in the background has STAT without + (not in the foreground process group).

Graceful exit vs forced termination: Write a script that will handle SIGTERM:
 data-l="bash"
 class="out" data-l="Expected output (example)"

When bash executes sleep 1 in the foreground, it will wait for it to end before running the trap, so the cleanup may be delayed by up to 1 second - this is why Systemd needs to give a timeout when stopping the service. %% represents the current job. KILL left behind a stale lock file: rm /tmp/worker.*.lock.

Create and observe zombies:
 data-l="bash"
 class="out" data-l="Expected output (example)"

kill -9 4612 will not make the zombie disappear; the parent process exits after 30 seconds, and the zombie is adopted by PID 1 and recycled immediately.

SIGHUP with nohup:
 data-l="bash"
 class="out" data-l="Expected output (example, after logging back in)"

PPID becomes 1 (or the user's systemd --user instance, depending on the session settings): it is orphaned and adopted. In addition, systemd-logind's KillUserProcesses=, if enabled, will kill such processes when logging out - it is not enabled by default in Ubuntu.

Cleanup: pkill -u "$USER" sleep; rm -f /tmp/worker.*.lock ~/linuxlab/tmp/sleep.pid(keep worker.sh).

Case 1: kill -9 caused database corruption

Problem: The staff on duty felt that Redis was shutting down too slowly, so they directly kill -9. The ongoing AOF rewriting was interrupted, and it took a long time to repair the file during restart. How to: Use the service manager to stop (systemctl stop redis-server, first TERM and then press timeout KILL); increase TimeoutStopSec if necessary (Lesson 2). Principle: KILL is only used after confirming that TERM is invalid.

Case 2: SSH disconnected, migration task terminated midway

Problem: A data migration script was run in the foreground for 4 hours in SSH. After the VPN was disconnected, the script received a SIGHUP and terminated, and the data was in a semi-migrated state. How to do it: Put the long task into the tmux session, or systemd-run --unit=migrate --same-dir ./migrate.sh and run it as a temporary service (the log enters journald, Lesson 2); the script itself is made reentrant.

Case 3: Thousands of zombie processes

Problem: The self-developed Python daemon forks a child process every time it processes a task, but never waits. After a few days, tens of thousands of appear in ps, and finally touch pid_max / cgroup pids.max limit, fork failed (Resource temporarily unavailable). How to: Fix the code (use subprocess.run or handle SIGCHLD); briefly restart the parent process to clear out all zombies. Monitoring: Alarm ps -eo stat | grep -c '^Z' (the node_exporter of the Prometheus class has process status indicators).

Common Errors and Solutions

kill: (1234) - Operation not permitted

Cause: You can only signal to processes with the same real/effective UID, unless you have CAP_KILL (root).

 data-l="bash"
The process still exists after kill -9

Reason: It is a zombie (Z, dead, waiting for recycling by the parent process), or in D state waiting for I/O.

 data-l="bash"

Fix: Zombie → Handle its parent process; D status → Troubleshoot storage/NFS (Lesson 7).

bash: fork: retry: Resource temporarily unavailable

Cause: The number of processes limit was reached: user's ulimit -u, cgroup's pids.max (systemd's TasksMax), or system's kernel.pid_max.

 data-l="bash"
The background task output confuses the terminal / the background task stopped by itself (Stopped (tty input))

Reason: The background job can still write to the terminal; it receives SIGTTIN when reading the terminal and stops.

 data-l="bash"
Command line operation questions
1. Find the 5 processes with the highest memory usage (display PID, user, %MEM, command).
 data-l="bash"
2. Stop all gunicorn processes of user myapp gracefully. If they still exist after 10 seconds, forcefully terminate them.
 data-l="bash"
Scenario analysis question
uptime shows that the load average of the 2-core machine is 12, but the CPU in top is 85% idle. What could it be? How to confirm?

Linux load statistics for tasks in R and D states. The CPU is idle but heavily loaded, indicating that a large number of tasks are in D state (waiting for disk, NFS, or other non-interruptible I/O). Confirm: ps -eo stat,pid,wchan:32,cmd | awk '$1 ~ /^D/', top's wa (iowait), vmstat 1's b column, iostat -x 1 to see the device delay; check whether the NFS mount is stuck and whether the disk is faulty. Lesson 7 dives into the USE method.

Verified teaching video

▶
How to use the kill command in Linux (Linux Crash Course Series) — Learn Linux TV
English · kill, pidof, signal and killall
▶
Using the ps Command | Efficient Process Monitoring on Linux Systems — Akamai Developers
English · Common options and output columns of ps

Official documentation

Video storyboard script (about 75 seconds)

This courseware cannot directly generate video/MP3. Storyboards and explanation scripts have been provided, which can be generated by video tools.

Shot 1 · 0–20s
Screen: PID, PPID, UID, status, fd table are listed on the process card; the /proc/4061 directory next to it is expanded.
Narration: A process is a running program plus its identity and open files, which can be seen in the proc directory.
Shot 2 · 20–45s
Screen: Press Ctrl+Z on the keyboard, the process card turns gray with T written on it; enter bg, the card turns green and moves to the "backstage" area on the right.
Narration: Ctrl+Z stops the foreground job, bg lets it continue in the background, and fg pulls it back.
Shot 3 · 45–75s
Screen: Two processes receive TERM and KILL respectively. The former cleans up the lock file before exiting, and the latter disappears instantly, leaving the lock file behind.
Narration: TERM is issued first to allow the program to exit gracefully, and KILL is the last resort.
Or score ≥ 70% on the Quiz

Module 6 · Package management: apt, dnf and repositories

35:00 – 42:00 · Package = file + metadata + installation script; repository = signed package index. The trust chain starts from the public key specified by Signed-By
7 minutesAPT 3.1 · deb822dnf 4.20(EL10)apt-key removed★★★★☆
Learning objectives
  • Explain packages, repositories, indexes, dependencies, signatures and Signed-By relationship; understand Ubuntu's default deb822 file /etc/apt/sources.list.d/ubuntu.sources.
  • Proficient in using apt (update / install / remove / purge / policy / hold / history) and dpkg (-l / -L / -S); know the difference between main, universe and -security, -updates.
  • Add the third-party repository in the correct way (keys are placed in /etc/apt/keyrings + .sources files) and no longer use the removed apt-key.
  • Compare RHEL system: dnf, rpm, /etc/yum.repos.d/*.repo, dnf history undo, version locking; understand Azure Linux's tdnf and Amazon Linux 2023 versioned warehouse.
Prerequisite knowledge:Module 2 (FHS), module 4 (sudo). Importance:★★★★☆

What: two families

Debian / UbuntuRHEL / Rocky / Alma / Amazon Linux / Azure Linux
Package format.deb (ar archive: control + data).rpm
Underlying tools (single package, no dependencies resolved)dpkg, database /var/lib/dpkgrpm, database /var/lib/rpm (EL10 is sqlite)
High-level tools (warehouse, dependencies, transactions)apt (interactive) / apt-get (script, stable output)dnf (EL10 is dnf 4.20; dnf5 for Fedora 41+); tdnf
Repository Configuration/etc/apt/sources.list.d/*.sources for Azure Linux 3.0 (deb822); legacy single line *.list Deprecated (removed no earlier than 2029)/etc/yum.repos.d/*.repo(INI)
Signing keysEach repository specifies its own public key with Signed-By: (/usr/share/keyrings or /etc/apt/keyrings)gpgcheck=1 + gpgkey=, imported into rpm database (rpm --import)
Installation scriptpreinst / postinst / prerm / postrm (can create users and start services)%pre / %post / %preun / %postun and scriptlets
Configuration file protectionconffile: Ask when upgrading the /etc file you changed%config(noreplace): The new version is saved as .rpmnew

Ubuntu's warehouse structure

 class="out" data-l="/etc/apt/sources.list.d/ubuntu.sources (26.04 example)"
ConceptValueMeaning
Suites(pocket)resolute / -updates / -security / -backportsVersion at release / stable update / security update / new version back-porting
Componentsmain (Canonical support), restricted (proprietary driver), universe (community maintenance, Ubuntu Pro provides extended security maintenance), multiverse (with license restrictions)redis-server in universe: If your source is only enabled main, you will get "Unable to locate package"
URIsOfficial or mirror address; the cloud is usually a regional mirror (such as Azure's azure.archive.ubuntu.com)You will see cloud mirrors in Lessons 3 and 4

Why: Why signatures are important

apt downloads the warehouse's InRelease (embedded signed Release file) and verifies it with the public key specified by Signed-By; the hash of the Packages index is listed in Release, and the hash of each .deb is listed in the index. SHA256. So a public key → Release → Index → ​​Package forms a chain of trust, which can be discovered even if the image is tampered with or uses HTTP. The old apt-key add put the third-party key into a global trust so that any repository could be signed with it - this is why it was deprecated and removed in APT 3 (26.04).

How: Steps for an apt install

  1. apt update: Download from sources InRelease → Verify signature → Download and verify Packages, Translation, etc. are indexed to /var/lib/apt/lists/.
  2. apt install redis-server: The solver (new for APT 3) computes dependencies (redis-tools, libjemalloc, etc.) with the version to install (the highest priority candidate in apt policy).
  3. Download .deb to /var/cache/apt/archives/ and verify the hash.
  4. Call dpkg --unpack (run preinst, unpack files) → dpkg --configure (run postinst: e.g. create redis system user, enable and start redis-server.service) → trigger (man-db, systemd daemon-reload).
  5. Logged to /var/log/apt/history.log and /var/log/dpkg.log; 26.04 can be viewed with apt history-list / apt history-info.

Debian/Ubuntu convention: Installing the service pack will automatically enable and start the service (the RHEL system does not start it by default, and requires systemctl enable --now). This is one of the most common behavioral differences between the two families.

When: Select the installation source

SourceAdvantagesRisk/cost
Distribution repository (apt/dnf)Security updates arrive automatically, are compatible with system libraries, and are auditableOlder version (LTS frozen main version)
Manufacturer's official warehouse (Docker, Microsoft, HashiCorp...)The latest version is still available apt UpgradeRequires trust in additional keys; use Signed-By to limit the scope
Snap(Ubuntu)Brings its own dependencies and automatically updatesAutomatic update timing needs to be managed; needs to be evaluated on the server
Language package manager (pip / npm) in the virtual environmentApplication dependencies and system isolation (myapp uses venv)Do not use sudo pip install Pollution system Python (Ubuntu will reject with externally-managed-environment)
curl … | sudo bashEasyNot auditable, non-rollback - production prohibited

RHEL system, Azure Linux, Amazon Linux 2023 Key points

  • EL10 repository: BaseOS (core OS) + AppStream (application, language runtime) + CRB (development dependency, enabled by default since AlmaLinux 10.1); EPEL provides additional community packages (dnf install epel-release). Modularity is deprecated in RHEL 10.
  • dnf commonly used: dnf install / remove / upgrade / search / info / provides / repolist / history / history undo N; version lock requires python3-dnf-plugin-versionlock.
  • Azure Linux 3.0: tdnf (Tiny DNF), the command is similar to dnf, the package collection is streamlined, mainly used for AKS nodes and container hosts.
  • Amazon Linux 2023: dnf; The warehouse is locked by release version (each AMI corresponds to a warehouse snapshot), use dnf check-release-update to check the new version, and then upgrade to the new releasever as needed (Lesson 4).
Common misunderstanding① “apt upgrade Will be upgraded to the next Ubuntu version" - No, that is do-release-upgrade; upgrade Only updated within the current version, full-upgrade Allows packages to be removed to resolve dependencies. ② "apt remove Deleted cleanly" - the configuration file is still there, purge was deleted only after deleting the conffile in /etc (data directories such as /var/lib/redis are usually still retained). ③ "It will take effect after installing the new kernel" - needs to be restarted (or Livepatch); /var/run/reboot-required prompts that a restart is required. ④ "apt-key can still be used" - APT 3.1 in 26.04 has been removed apt-key. ⑤ "dnf and apt will automatically start the service" - Ubuntu will, but RHEL will not.

Chain of trust: from public key to package

Public key (Signed-By)ubuntu-archive-keyring.gpg Verification InReleaseEmbedded OpenPGP signatureList indexed SHA256 Hash Packages(.xz) IndexPer package: version, dependencyFilename, SHA256 Hash redis-server_…_amd64.deb/var/cache/apt/archives/→ dpkg unpacking and configuration Local status /etc/apt/sources.list.d/*.sources warehouse definition /var/lib/apt/lists/ Downloaded index (apt update) /var/lib/dpkg/status Installed package database /var/log/apt/history.log · dpkg.log audit records When the trust chain is broken NO_PUBKEY / signatures couldn't be verified Hash Sum mismatch (the image is out of sync or tampered with/proxy cache) does not have a Release file (wrong package name or EOL) → apt refuses to use this warehouse (safe default)
Figure 6-1 As long as the public key is trusted, even if the image is not trusted and the transmission is HTTP, the package content cannot be quietly tampered

apt install redis-server full process

Select a scenario and observe each step of apt and dpkg step by step; the failure scenario displays the actual error text and repair methods.

Ready.
The real mechanism corresponding to the animationapt and dpkg are mutually exclusive through the lock file /var/lib/dpkg/lock-frontend and /var/lib/dpkg/lock ; Ubuntu's unattended-upgrades Security updates are installed every day by default, and the lock is often held shortly after booting. The postinst of the service package is deb-systemd-helper enabled and deb-systemd-invoke started the service (complying with policy-rc.d, starting is usually prohibited in container images).

Command comparison table

TaskUbuntu(apt / dpkg)RHEL system (dnf/rpm)
Refresh indexsudo apt updatesudo dnf makecache (usually automatic)
Install/specify versionsudo apt install pkg / pkg=1.2-3sudo dnf install pkg / pkg-1.2-3
Upgrade allsudo apt upgrade (full-upgrade allows package deletion)sudo dnf upgrade
Only install security updatesunattended-upgrades (enabled by default)sudo dnf upgrade --security
Delete / delete with configurationapt remove / apt purge; apt autoremovednf remove (automatically clean up unnecessary dependencies)
Search/Detailsapt search / apt show pkgdnf search / dnf info pkg
Candidate versions and sourcesapt policy pkgdnf list --showduplicates pkg
Which package the file belongs todpkg -S /pathrpm -qf /path / dnf provides /path
What files are in the packagedpkg -L pkgrpm -ql pkg
Installed listdpkg -l / apt list --installedrpm -qa / dnf list --installed
Fixed versionsudo apt-mark hold pkgsudo dnf versionlock add pkg (plugin)
History/rollbackapt history-list (APT 3), /var/log/apt/history.log; rollback requires manual installation of the old versiondnf history / dnf history undo N
Verify installed filesdpkg --verify pkgrpm -V pkg
 data-l="bash"
 class="out" data-l="Expected output (example, excerpt)"

How to verify: Version number 5:8.0.5-1ubuntu0.1 Medium 5: Yes epoch, 8.0.5 is the upstream version, and -1ubuntu0.1 is the Ubuntu packaging revision (check the resolute version on packages.ubuntu.com). Older systems may still have /etc/apt/sources.list (comments only). URIs in cloud images point to cloud vendor images. Common mistakes: Use apt instead of apt-get in Dockerfile/scripts (apt will warn "does not have a stable CLI interface").

Standard mode for adding a third-party warehouse (take the Docker official warehouse as an example, used in the Docker class)

 data-l="bash"

Key points: the key is only effective for this warehouse (Signed-By); .asc (ASCII) and .gpg (binary) is acceptable; whether the manufacturer has provided a repository for a new release (such as resolute) shall be subject to its documentation. No real additions are needed for this lesson.

Goal: Install the system dependencies (redis-server, python3-venv) required by myapp, query, fix and audit. Environment:linuxlab, labadmin. Cost: Download approximately 10–20 MB.

Update and install:
 data-l="bash"
 class="out" data-l="Expected output (example)"

Ubuntu's postinst automatically enables and starts Redis. It only listens on 127.0.0.1 (bind in /etc/redis/redis.conf).

What does this package and who does it belong to:
 data-l="bash"
 class="out" data-l="Expected output (example)"

Pay attention to the package maintainer's approach: dedicated system user + nologin + data directory 750 - consistent with the approach of myapp in the comprehensive experiment. The specific file list, permissions and UID are subject to your system.

Fixed version and audit history:
 data-l="bash"
 class="out" data-l="Expected Output (Example, 26.04)"

apt history-list is a new command for APT 3 (26.04), and the column format is an example; use /var/log/apt/history.log on 24.04. Hold is suitable for critical components that "must be tested before upgrading", but will prevent security updates from arriving and must be released in a planned manner.

Do you need to restart? :
 data-l="bash"
Compare RHEL system (optional, in rhellab):
 data-l="bash"

RHEL 10 series AppStream provides Valkey instead of Redis (the package name and availability are subject to the actual output of dnf info); the service will not start automatically after the RHEL system is installed: sudo systemctl enable --now valkey.

Cleaning: Keep redis-server and python3-venv (for comprehensive experiments).

Case 1: Automated deployment always fails after booting

Problem: After the new VM is started, cloud-init executes apt install immediately, and intermittently reports Could not get lock /var/lib/dpkg/lock-frontend——unattended-upgrades Security updates are being installed. How to: Use apt-get -o DPkg::Lock::Timeout=300 install … to wait for the lock; or use the packages: module in cloud-init (Lessons 3 and 4). Forbidden: Deleting the lock file or killing dpkg will cause damage to the package database.

Case 2: An apt upgrade introduced an incompatible major version

Problem: The third-party warehouse does not have a fixed version. apt upgrade upgrades the database client from 15 to 17, and the application connection fails. How to: Use apt preferences (/etc/apt/preferences.d/ Pin) or apt-mark hold to fix the major version; upgrade first in the pre-release environment; incorporate the upgrade into the change process (Lesson 3 Azure Update Manager, Lesson 4 Patch Manager).

Case 3: Hash Sum mismatch of internal mirror source

Problem: Enterprise proxy caches old Packages index but InRelease has been updated, all servers apt update report Hash Sum mismatch. How to do it: The proxy pair InRelease/Packages does not cache or set a short TTL; use an image that supports by-hash (Ubuntu repository provides Acquire-by-hash by default). Temporary solution: sudo rm -rf /var/lib/apt/lists/* && sudo apt update.

Common errors and solutions

E: Unable to locate package xxx / Package 'xxx' has no installation candidate

Cause: No apt update; wrong package name; the component (universe) is not enabled; the package is not in the current release.

 data-l="bash"

Fixed: After adding universe to Components of ubuntu.sources, apt update.

W: GPG error: … NO_PUBKEY 7EA0A9C3F273FCD8 / The repository … is not signed

Cause: Signed-By points to a key file that does not exist, is not the corresponding public key, or the key has expired/rotated.

 data-l="bash"

Fix: Re-download the key from the manufacturer's official HTTPS address to the path pointed by Signed-By; Do not add [trusted=yes] to bypass verification.

E: Could not get lock /var/lib/dpkg/lock-frontend. It is held by process 1234 (unattended-upgr)
 data-l="bash"

Fix: Wait for it to complete. Do not rm lock files.

E: dpkg was interrupted, you must manually run 'sudo dpkg --configure -a' to correct the problem.
 data-l="bash"
error: externally-managed-environment(sudo pip install)

Reason: Ubuntu's system Python is managed by apt (PEP 668), which prohibits direct writing by pip.

 data-l="bash"
Command line operation questions
1. Find out which package /usr/bin/jq belongs to, and list the version and source repository of the package.
 data-l="bash"
2. List the packages installed or upgraded through apt in the last 7 days (applicable to 24.04 / 26.04).
 data-l="bash"
Scenario analysis question
The vendor's installation document requires the execution of curl -fsSL https://vendor.example/install.sh | sudo bash. How would you evaluate and adapt?

Risk: The content of the script cannot be audited, each download may be different, run as root, cannot be rolled back, if the transmission or provider is compromised, it will be completely lost. Transformation: Download the script and review it (fixed version/hash); give priority to using the vendor's signed apt repository (/etc/apt/keyrings + .sources + Signed-By), so that both upgrades and uninstallations go through the package manager; verify in the pre-release environment; write the repository and version into configuration management (Ansible class). If you can only use a script, verify SHA256 after downloading and run it in an isolated environment.

Verified teaching video

▶
Linux Crash Course - The apt Command — Learn Linux TV
English · apt installation, search, upgrade, deletion; recorded before deb822 became the default, the sources format is subject to this lesson
▶
Linux Crash Course - The dnf Command — Learn Linux TV
English · dnf installation, search, upgrade and dnf-automatic

Official documentation

Video storyboard script (about 75 seconds)

This courseware cannot directly generate video/MP3. Storyboards and explanation scripts have been provided, which can be generated by video tools.

Shot 1 · 0–20s
Screen: A key (Signed-By) opens the lock of InRelease, the hash on InRelease is connected to Packages, and the hash of Packages is connected to .deb.
Narration: apt's trust chain starts with a public key, and uses hashes to lock indexes and packages layer by layer.
Shot 2 · 20–50s
Screen: apt install redis-server: dependency tree expansion, download progress bar, dpkg unpacking, postinst creates redis user and starts service.
Narration: apt is responsible for the warehouse and dependencies, dpkg is responsible for unpacking and running the installation script, and Ubuntu will start the service smoothly.
Lens 3 · 50–75s
Screen: left and right split screen, left apt policy, right dnf list --showduplicates; bottom says hold / versionlock.
Narration: The two families have different commands but the same idea: check candidate versions, fix critical versions, and record every change.
Or score ≥ 70% on the Quiz

Module 7 · Text processing: grep, sed, awk and pipes

42:00 – 50:00 · Logs, configurations, and command outputs are all text; small tools are strung together with pipes to form the fastest analysis platform
8 MinutesGNU grep / sed · mawk(Ubuntu)/ gawk(RHEL)Edit in place and back up first★★★★★
Learning objectives
  • Use grep (-E -i -v -c -o -n -r -w) to filter lines according to regular rules; distinguish basic regular rules (BRE) and extended regular rules (ERE).
  • Use sed for replacement, deletion, line range processing, and safe in-place editing of configuration files (-i.bak).
  • Use awk to process by fields: -F, $1...$NF, conditions, BEGIN/END, associative array aggregation.
  • Use sort, uniq -c, cut, tr, wc, head/tail, tee, xargs combined pipeline to answer "Top IP, 5xx distribution, P95 "Delay" issues.
Prerequisite knowledge:Module 2 (quotation marks, redirection, pipe). Importance:★★★★★

What: Three main tools

ToolsMental modelMost commonly used
grepMatch regular rules line by line, select linesgrep -E ' 5[0-9]{2} ' access.log, grep -rn 'bind' /etc/redis/, grep -v '^#' f
sedStream editor: execute "address + command" line by line, rewrite liness/old/new/g, /^#/d, -n '10,20p', -i.bak
awkSplit into fields line by line, execute "mode {action}", calculation and reportawk '{print $1}', awk -F: '$3>=1000', {c[$9]++} END{for(k in c) print k,c[k]}

Implementation differences: Ubuntu's default awk is mawk (small and fast), the RHEL system is gawk (GNU, with many extensions, such as asort, --csv); use awk -W version or awk --version to check, and when you need gawk features, sudo apt install gawk. grep and sed are GNU versions on both sides (not part of coreutils, not affected by the 26.04 rust-coreutils switch; sort, uniq, cut, tr, wc belong to coreutils).

Regular expression quick overview

WritingMeaningBRE (grep / sed default)ERE(grep -E / sed -E / awk)
^ $Start of line / End of line✓✓
. * [a-z] [^0-9]Any character / previous item repeated 0+ times / character class / negative class✓✓
+ ? {2,3} | ( )1+ times / 0–1 times / times / or / groupingNeeds to be written as \+ \? \{2,3\} \| \( \) (GNU extension)Use directly
[[:digit:]] [[:space:]]POSIX character class✓✓
\b \dWord boundary/number\b is a GNU extension; \d is only available in grep -P (PCRE)

Why: Why learn these "old tools"

  • Any Linux It is available on all platforms (including a minimized cloud image and rescue environment), and does not rely on the network or additional installation.
  • Streaming processing: Several GB of logs do not need to be read into memory; both ends of the pipeline run concurrently.
  • Combines naturally with output from the journalctl, kubectl, az/aws CLI (JSON with jq, Lesson 5).

How: Pipeline data flow

 class="out" data-l="Top 3 Access IP"

uniq only merges adjacent duplicate rows, so it is almost always sort | uniq -c. Sorting is affected by locale: use LC_ALL=C sort when endianness is required in scripts (also faster).

When: Which tool to choose

TaskPreferred
Find out the line containing a certain pattern and which file a certain configuration is ingrep(-r, -l, -n)
Batch modify a row in the configuration, delete commentssed (backup before modification in production or use configuration management instead)
Statistics by column, sum, average, group count, formatted reportawk
Get columns by fixed delimitercut -d: -f1
Character replacement/deletion (uppercase and lowercase, delete carriage return)tr
Convert input into command parametersxargs (when the file name contains spaces -0 cooperate with find -print0)
JSON / YAMLjq / yq, do not use grep to parse JSON
Common misunderstanding① “cat file | grep x is the standard way of writing" - directly grep x file, one less process. ② "sed -i is safe" - it will replace the file (new inode), the symbolic link will be replaced with a normal file, and the permissions and owners may change; first use the command without -i to preview, and then -i.bak. "awk's $0 is the 0th column" - $0 is the entire row, $NF is the last column ④ "grep -c Statistics matching times" - the statistics are the number of matched rows, the number of statistics is grep -o … | wc -l. ⑤ " . Matching point in the regular expression" - it matches any character, matches IP The points in need to be written \..

Pipeline: concurrently running process chain

access.log2000 lines grep -E' 5[0-9]{2} ' awk'{print $7}' sortRequired to read the input uniq -cAdjacency count sort -nr | headReport Each | is a kernel pipeline buffer (default 64 KiB): writer blocking when full, reader blocking when reading empty → natural flow control grep and awk output while reading (streaming); sort must read all input before outputting (large files will use /tmp Temporary file) head will exit after reading N lines → receive SIGPIPE when upstream writes again and exit quietly (module 5) stderr does not enter the pipe: use 2>&1 or |& (module 2) when necessary
Figure 7-1 All processes in the pipeline start at the same time; they belong to the same process group, and Ctrl+C will terminate them together

awk's execution model

BEGIN { … }Execute once before reading any linesSet FS, print header For each row: split into $1 ... $NF (by FS, default blank)Mode { action } will be executed only when the mode is true; omit mode = executed per row$9 >= 500 { err[$7]++ } { sum += $NF; n++ }Built-in variables: NR row number · NF field number · FS/OFS separator · FILENAME END { … }Execute after all rows are processedOutput aggregation resultsfor (k in err) print k, err[k]
Figure 7-2 Associative array (err[$7]++) is the core of awk's "group counting"

Pipeline step-by-step simulator

Data: 12-line sample of access.log (same format as generated in environment preparation: IP - - [Time] "Method Path Protocol" Status Bytes "-" "UA" Time consuming). Select a pipeline and step through the output of each command - the results are generated by JavaScript in the page. Computed by the true semantics of the command

Input (previous level output)
 class="out" data-l="stdin" id="a7in" style="min-height:220px;white-space:pre-wrap;font-size:12px"
This level output
 class="out" data-l="stdout" id="a7out" style="min-height:220px;white-space:pre-wrap;font-size:12px"
Ready.

Command table

CommandsCommon optionsExamples
grep-E ERE, -i Ignore case, -v inverse selection, -c count lines, -o output only matches, -n line number, -r recursive, -l list only file names, -w whole words, -A/-B/-C contextgrep -rnw /etc -e 'PermitRootLogin'
sed-n does not print automatically, -E ERE, -i[.bak] edit in place; command s p d a i csed -n '/ERROR/,+2p' app.log
awk-F delimiter, -v var=valueawk -F: '{print $1}' /etc/passwd
sort-n numbers, -r reverse order, -k2,2 by column 2, -t: delimiter, -u deduplication, -h human readable sizedu -sh /var/* | sort -h
uniq-c Count, -d only show duplicatessort | uniq -c
cut / tr / wc-d -f / -d -s 'a-z' 'A-Z' / -l -w -ctr -d '\r' < win.txt > unix.txt
head / tail-n, tail -f trace, tail -n +2 skip headertail -F /var/log/syslog
tee-a appendcmd | tee out.txt | grep x; echo x | sudo tee /etc/f
xargs-0, -n, -P Parallel, -I{}find . -name '*.log' -print0 | xargs -0 -n 50 gzip
diff / comm-u Unified formatdiff -u redis.conf.bak redis.conf
 data-l="bash"
 class="out" data-l="Expected output (example, numbers depend on generated data)"
 data-l="bash"
 class="out" data-l="Expected output (example)"

The log itself is sorted by time, so "per minute" statistics do not need to be sorted first. For log analysis in production, see Lesson 2 journald and Prometheus & Grafana Lesson (logs are not suitable for long-term calculation of latency quantiles).

Goal: Use pipelines to answer 5 operational questions and safely modify a copy of the configuration using sed. Environment:linuxlab, ~/linuxlab/logs/access.log (generated during environment preparation). Fees: None.

Question 1: Which IP has the most requests? Is it abnormal?
 data-l="bash"
 class="out" data-l="Expected output (example)"

203.0.113.7 (document reserved address) is weighted 6x in the generated data, accounting for about 1/4 of the traffic - in a real environment this is a signal to investigate.

Question 2: What did this IP access and how many failed?
 data-l="bash"
Question 3: The slowest 5 requests
 data-l="bash"
Question 4: Which accounts in /etc/passwd can log in?
 data-l="bash"
 class="out" data-l="Expected output (example)"
Question 5: What are the settings that actually take effect in the Redis configuration? (Remove comments and blank lines)
 data-l="bash"
 class="out" data-l="Expected output (example)"

The line number and default value change with the Redis version; maxmemory is commented out by default.

sed safe editing (practice on a copy):
 data-l="bash"
 class="out" data-l="Expected output (example)"

We don't install it back into /etc/redis: the actual modification of the service configuration belongs to Lesson 2 (Modify → Verify → Restart → Verify → Rollback). Note that -i.bak only backs up the first time; it will not back up the second time if -i does not have a suffix.

Cleanup: rm ~/linuxlab/tmp/redis.conf*(keep access.log).

Case 1: Locating the source of the attack within 5 minutes of the incident

Problem:Surge of website 502. How to do it:awk '$9==502 {print $1}' access.log | sort | uniq -c | sort -nr | head Found that a single network segment accounts for 80%, grep and its User-Agent is a scanner; block it on load balancing/WAF (Lesson 6 Firewall). Experience: Use pipes to get "who, when, what" first, and then decide on actions; save commonly used pipes as scripts (Lesson 5).

Case 2: sed turns the configuration file into an empty file

Problem:Operation and maintenance wrote sed 's/a/b/' app.conf > app.conf, Shell first opened (cleared) the file with O_TRUNC, and sed read an empty file. How to do it: Use sed -i.bak or write a temporary file mv; the key configuration is managed by the configuration rendering template (Ansible class).

Case 3: grep parsing JSON output leads to misjudgment

Problem: The script uses grep '"status": "ok"' to determine health. After the cloud CLI upgrade, the output format (spaces, field order) changes, and false positives are monitored. How to: Use jq -e '.status == "ok"' for structured data, or call CLI's --query/--output tsv (lessons 3 and 4).

Common errors and solutions

sed: -e expression #1, char 12: unknown option to `s'

Cause: The replacement content contains the delimiter / (such as path).

 data-l="bash"
awk: line 1: syntax error at or near … / The variable is not replaced

Reason: The awk program uses double quotes, and the Shell expands $1 first; or you want to pass in the Shell variable.

 data-l="bash"
grep: (standard input): binary file matches

Cause: The file contains non-text bytes such as NUL (binary and UTF-16 encoding are mixed in the log).

 data-l="bash"
The sort result is "out of order": 10 is in front of 9 / different machines sort differently

Reason: Sort lexicographically instead of numerically; locale is different.

 data-l="bash"
Command line operation questions
1. Count the proportion of requests for each HTTP status code in access.log (percentage, keep 1 decimal place).
 data-l="bash"
2. Recursively find all file names containing 127.0.0.1 under /etc (permission errors will not be displayed).
 data-l="bash"
Scenario analysis question
A 30 GB log file needs to count the number of requests for each URL. sort | uniq -c took a long time and /tmp was full. How to improve?

sort needs to sort all data externally and will write a large number of files in the temporary directory. Change to awk associative array traversal once: awk '{c[$7]++} END {for (k in c) print c[k], k}' big.log | sort -nr | head, the memory is only related to the number of different URLs; if sorting is necessary, use LC_ALL=C sort -S 2G -T /data/tmp --parallel=4 to specify the memory, temporary directory and parallelism; first grep / awk filter out unnecessary lines; the long-term solution is to send the logs to the logging platform.

Verified teaching video

▶
Linux Crash Course - The grep Command — Learn Linux TV
English · Common options and regular expressions of grep
▶
Linux Crash Course - The sed Command — Learn Linux TV
English · Replacement, deletion and in-place editing
▶
Linux Crash Course - awk — Learn Linux TV
English · Fields, patterns and actions
▶
Linux Crash Course - The cut Command — Learn Linux TV
English · Get columns by delimiter and character position

Official document

Video storyboard script (about 75 seconds)

This courseware cannot directly generate videos/MP3s. Storyboards and explanation scripts have been provided, which can be generated by video tools.

Shot 1 · 0–20s
Screen: 2000 lines of logs flowing down like a waterfall, grep like a sieve leaving only the lines with 500.
Narration: grep is responsible for selecting rows, sed is responsible for changing rows, and awk is responsible for calculating by columns.
Shot 2 · 20–50s
Screen: awk cuts a row into 13 grids, and the 7th grid (path) is thrown into counting buckets.
Narration: awk's associative array is a group counter, and you can get the number of errors for each path in one traversal.
Shot 3 · 50–75s
Screen: Five processes are connected in a row with pipes and run simultaneously, and finally the list of Top 3 IPs is output.
Narration: The processes in the pipeline run at the same time, and the data is transferred like an assembly line. Sort plus uniq bar c is the most classic combination.
Or score ≥ 70% on the Quiz

Module 8 · Getting Started with System Readiness Review and Troubleshooting

50:00 – 60:00 · Before delivering a machine, use 12 The inspection confirms that it is "healthy, maintainable, and has no obvious security holes"; when problems occur, narrow the scope in a fixed order
10 minutes12 readiness reviewsObserve first, then modify★★★★★
Learning objectives
  • Perform 12 system readiness reviews: version and support period, patches and reboots, time, disks and inodes, memory, load, failed services, listening ports, administrators and sudo, dangerous accounts, dangerous permissions, error logs.
  • Master the general process of troubleshooting: Reproduction → Read the original text of the error → Positioning level (Shell/Permissions/Process/Package/Resource) → Single-variable verification → Repair → Verify → Record.
  • Proficiently identify the five most common types of errors: command not found, Permission denied, No space left on device, Address already in use, Connection refused.
  • Deliberately create 4 faults on the lab VM and repair them according to the troubleshooting tree.
Prerequisite knowledge:Modules 1–7. Importance:★★★★★

What: 12 system readiness reviews

#Check itemsCommandsPass standardsModules
1Releases and support cycles. /etc/os-release; echo $PRETTY_NAMESupported LTS (26.04 / 24.04); EOL documentedM1
2Patches and rebootsapt list --upgradable; ls /var/run/reboot-requiredNo security updates to be installed; no pending restarts (or scheduled)M6
3Time synchronizationtimedatectlSystem clock synchronized: yes; the time zone complies with the specification (the server commonly uses UTC)No. 2 Lesson
4Disk space and inodedf -hT -x tmpfs; df -iUsage < 80%M2
5Memory and swapfree -havailable Sufficient; no continuous pagingM5
6Loaduptime; nproc15 minute load M5
7Failed Servicesystemctl --failed0 loaded units listedLesson 2
8Listening Portssudo ss -ltnupOnly the expected ports (22, native 6379, 5000); no unexpected 0.0.0.0 ListeningM5, Lesson 2
9Admins and sudogetent group sudo; sudo visudo -cAdmin list is as expected; sudoers syntax is correct; no broad NOPASSWD ALLM4
10Dangerous accountsawk -F: '$3==0' /etc/passwd; sudo awk -F: '$2==""' /etc/shadowOnly root has UID 0; no empty passwordM4
11Dangerous permissionssudo find / -xdev -type f -perm -o+w; SUID listNo files writable by others; SUID consistent with baselineM3
12Error logjournalctl -p err -b --no-pager | tailNo unexplained duplicate errorsLesson 2

Why: Why should we "review" instead of "look almost the same"

  • The root causes of most production accidents are mundane: full disk, incorrect certificate/time, service not set to start automatically at boot, permissions changed, and patches not applied. 12 checks cover them.
  • The review results can be written into scripts (Lesson 5), written into configuration management (Ansible lesson), and access monitoring (Prometheus lesson), changing from one-time inspection to continuous assurance.
  • The handover is well documented: "This machine passed the review on 2026-11-17, and the exceptions are...".

How: General process for troubleshooting

  1. Reproduce and copy the original text of the error: complete error message, exit code (echo $?), and time point. Don't rely on impressions.
  2. Location level: Is it Shell command not found (127)? Permissions (EACCES/EPERM)? Resources (ENOSPC, memory, fd, number of processes)? Network (deny/timeout/DNS)? An error in the program itself?
  3. Look at the evidence: ls -l/namei -l, id, df, ss, ps, log (journalctl -u service -e). If necessary, strace -f -e trace=file,network to see the last failed system call.
  4. Only change one variable at a time, back up before changing (cp -a f f.bak.$(date +%F)), and verify immediately after changing.
  5. Fix root causes and prevent recurrence: Include readiness reviews, monitoring, or automation; write incident logs.
Original error messageerrnoFirst reaction
command not found—(Shell search failed, 127)type -a, PATH, whether to install or not
Permission deniedEACCESid, namei -l, ACL, AppArmor
Operation not permittedEPERMRequires capability (root), sticky, chattr +i
No such file or directoryENOENTPath spelling, symbolic link target, shebang interpreter
No space left on deviceENOSPCdf -h and df -i, du find files in large directories that have been deleted but are still open
Address already in useEADDRINUSEsudo ss -ltnp 'sport = :5000'
Connection refusedECONNREFUSEDNo one is monitoring the peer port: the service is not started or only listens to 127.0.0.1
Too many open filesEMFILEulimit -n, ls /proc/PID/fd | wc -l
Common misunderstandings① "Try restarting first" - Restarting may temporarily eliminate symptoms and also destroy evidence (process state, temporary files, in-memory logs); collect evidence first before restarting. ② "df shows that there is still space, so it is not a disk problem" - the inode may be exhausted (df -i), or the file has been deleted but is still open by the process (sudo lsof +L1). ③ "Connection refused is a firewall" - Firewall packet loss usually manifests astimeout; refused means that the other host clearly replies "No one is listening on this port". ④ “Do the review only once” – the machine will drift, and the review should be performed automatically and regularly.

Error reporting → Level → Tool

① Recurrence · Copy the original text of the error · echo $? · Record time "What happened" instead of "What I think it is" Shell / Command127 / 126type -a · PATHfile · head -n1bash -x scriptM1 · M2 Identity and PermissionsEACCES / EPERMid · namei -lgetfacl · sudo -lAppArmor LogM3 · M4 Process and ServiceNot running / stuck / zombieps · pgrep · systemctlss -ltnp · lsofjournalctl -uM5 · Lesson 2 Software packageCannot be installed / wrong versionapt policydpkg -S / -Lhistory.logM6 ResourcesENOSPC / OOM / EMFILEdf -h · df -i · dufree · dmesgulimit · lsof +L1M8 · Lesson 7 ③ Single variable repair → immediate verification → record (timeline, root cause, repair, prevention)Before modification: cp -a file file.bak.$(date +%F) · After modification: Re-execute the command that failed initially
Figure 8-1 The original error message usually tells you which layer you are on; when troubleshooting across layers, go from bottom to top (resources → process → permissions → commands)

Readiness Score Card

Select the status of a host, click "Run Review", and perform 12 checks one by one: each item displays the real command and (example) output, and gives pass/warning/fail and repair suggestions. "Linuxlab before delivery" is the state you should be in after completing this lesson.

Select a host and run the review; click on any check item to view the command and output.

One-click review script (read-only)

 data-l="bash"
 class="out" data-l="Expected Output (example, excerpt)"

This script itself is a comprehensive application of this lesson: built-in and external commands, redirection, pipes, awk filtering, sudo, and permissions. Lesson 5 will turn this into engineering (set -euo pipefail, ShellCheck, testing); the Ansible lesson will turn it into fact collection across multiple hosts.

Commonly used commands for troubleshooting

CommandPurpose
sudo ss -ltnp 'sport = :5000'Who is listening to port 5000
sudo lsof -i :5000 / sudo lsof +L1The process corresponding to the port / Deleted but still open files
du -xh --max-depth=1 / 2>/dev/null | sort -h | tailFind large directory
sudo dmesg -T | tail / journalctl -kKernel messages (OOM, disk errors, AppArmor)
journalctl -u redis-server -e --no-pagerRecent logs of a service
strace -f -e trace=%file,%network -o t.txt cmdFind the last failed system call (grep -E '= -1' t.txt | tail)
curl -sv http://127.0.0.1:5000/healthzApplication layer verification

Objective: Deliberately create 4 faults and process them according to "error report → layer → evidence → repair → verification"; final run readiness review. Environment:linuxlab. Fees: None.

Fault 1: The script cannot be executed
 data-l="bash"
 class="out" data-l="Expected Output (example)"

126 → The level is "execution permission"; the permission of the symbolic link itself does not matter, what is seen is the target file.

Fault 2: Disk full (safely simulated in a 5 MB tmpfs)
 data-l="bash"
 class="out" data-l="Expected Output (example)"

Space is not released after file deletion because fd 3 still has it open (number of links is 0); space is not reclaimed until fd is closed. It is common in production that deleted logs are still written by the service process - restart or let the service reopen the log (Lesson 2 logrotate).

Fault 3: Port occupied
 data-l="bash"
 class="out" data-l="Expected output (example, excerpt)"

Myapp will use port 5000 in the comprehensive experiment - be sure to kill %1 to release it.

Fault 4: The dependent service is unavailable
 data-l="bash"
 class="out" data-l="Expected output (example)"

Connection refused + No monitoring → The service is not running. Lesson 2 will let myapp.service declare a dependency on redis-server (Wants=/After=).

Run readiness review: Execute readiness.sh in the "Command" tab, save the results to ~/linuxlab/logs/, and compare the passing standards item by item; record the reasons and plans when there are failures.
Cleaning: sudo rmdir /mnt/small; Confirm sudo ss -ltn 'sport = :5000' No output.

Case 1: Disk 100% but du cannot find large file

Problem: Root partition is full, du -sh /* only adds up to half. Root cause: The application log was deleted by rm, but the process still holds the file handle and continues to write. Method:sudo lsof +L1 Find the process and let it reopen the log (restart the service or send the signal agreed by the application); later use logrotate's copytruncate or let the application support reopening (Lesson 2).

Case 2: inode exhausted

Problem:No space left on device, but df -h only uses 40%. Root cause: Millions of small files have accumulated in the session file directory, df -i shows 100%. How to do:find /var/lib/php/sessions -type f -mmin +1440 -delete Clean, and configure periodic cleanup (systemd-tmpfiles or timer, Lesson 2); add df -i to the readiness review.

Case 3: "Time bomb" found in delivery review

Problem: Found in the new environment review: time is not synchronized (deviation of 7 minutes, which will cause TLS and cloud API signature failure), there is a legacy ALL=(ALL) NOPASSWD in /etc/sudoers.d/temp: ALL, the redis monitoring of the two machines is at 0.0.0.0. How to do it: After the repair, incorporate the 12 checks into the online access control and continue to check through monitoring (Prometheus & Grafana class).

Interactive troubleshooting tree

Start from symptoms, answer questions step by step, and get diagnostic commands and repair methods. Covers common faults in all modules of this course.

Command line operation questions
1. Find the five largest directories in the root file system (not across file systems).
 data-l="bash"
2. List all TCP ports and their processes listening on non-loopback addresses.
 data-l="bash"
Scenario analysis question
Early morning alarm: myapp returns 500, OSError: [Errno 28] No space left on device appears in the log, but df -h shows that / is only used 62%. Please write down the troubleshooting steps.

① Confirm which path failed to write (log/temporary directory), use df -h to see the file system where it is located - it may be a separately mounted /var or /tmp (tmpfs) instead of /; ② df -i Check inode; ③ sudo lsof +L1 Check deleted files that are still occupied; ④ du -xh --max-depth=1 Find the growing directory; ⑤ Release space (clean, rotate, expand), re-verify /healthz; ⑥ Prevention: disk and inode alarms (80%), log rotation, temporary file cleaning strategy, and write it down in the incident record.

Verified teaching video

▶
60 Linux Commands you NEED to know (in 10 minutes) — NetworkChuck
English · Quick review of the commands in this lesson
▶
100+ Linux Things you Need to Know — Fireship
English · General review of concepts: processes, permissions, package management, pipelines, etc.
▶
The 50 Most Popular Linux & Terminal Commands - Full Course for Beginners — freeCodeCamp.org
English · Long command practice

Official document

Video storyboard script (about 80 seconds)

This courseware cannot directly generate video/MP3. Storyboards and explanations have been provided, which can be generated by video tools.

Shot 1 · 0–20s
Screen: The scorecard composed of 12 grids lights up green one by one, with "Time Synchronization" and "Listening Port" turning red.
Narration: Before delivering a machine, use twelve inspections to confirm that it is healthy, maintainable, and has no obvious safety holes.
Shot 2 · 20–55s
Screen: Five original error messages are arranged in a row, each connected to a level: command, permission, process, package, resource.
Narration: The original text of the error report usually tells you which layer the problem is at: 127 means commands, Permission denied means permissions, and Connection refused means no one is listening.
Shot 3 · 55–80s
Screen: Disk 100%, still showing 100% after the file is deleted, lsof marked (deleted), reset to zero after closing the handle.
Narration: First collect evidence, then only change one variable at a time, and verify it immediately after the change.
Or score ≥ 70% on the Quiz

Command cheat sheet

All commonly used commands in this lesson are grouped by tasks; the differences between Ubuntu and RHEL systems are marked separately
Ubuntu 26.04 / 24.04~/linuxlab

System identity

 data-l="bash"

Shell and expansion

 data-l="bash"

Files and directories

 data-l="bash"

Permissions and ACL

 data-l="bash"

Users, groups and sudo

 data-l="bash"

Processes and signals

 data-l="bash"

Software packages (Ubuntu)

 data-l="bash"

Software package (RHEL system)

 data-l="bash"

Text processing

 data-l="bash"

Troubleshooting

 data-l="bash"

Exit code and error report quick check

PhenomenaMeaningCheck first
$? = 127 / command not foundCommand search failedtype -a, PATH, installation
$? = 126 / Permission denied (when executing)Found but unable to executex bit, noexec, directory x on path
$? = 128+N(130 / 137 / 143)Terminated by signal N (INT/KILL/TERM)Who sent the signal? OOM? dmesg
Permission denied / Operation not permittedEACCES / EPERMid, namei -l, ACL, sticky, chattr
No space left on deviceENOSPCdf -h, df -i, lsof +L1
Address already in use / Connection refusedPort occupied/no one listeningss -ltnp, service status
Could not get lock /var/lib/dpkg/lock-frontendAnother apt/dpkg is runningWaiting; DPkg::Lock::Timeout
NO_PUBKEY / not signedRepository signature cannot be verifiedKey pointed to by Signed-By

Comprehensive experiment + final exam

Manually deploy myapp (Flask + gunicorn + Redis, port 5000) as the system user myapp in /opt/myapp, set the file with minimum permissions, and stop after acceptance - Lesson 2 turns it into myapp.service
≈ 25 minutesLocal · FreeStarting point for Lesson 2, please keep

Scenario

The team wants to run myapp on linuxlab (the same sample application as the Docker / Jenkins lesson, no container is used here, running directly as a native process). Security requirements: The application runs as a dedicated non-loginable system user; the application cannot modify its own code; the configuration (including future passwords) is only changeable by root, readable by myapp, and invisible to others; dependencies are installed in a virtual environment and do not pollute the system Python; Redis only monitors the local machine.

PathOwner: GroupModeReason
/opt/myapproot:myapp0750myapp can enter; others (including alice) cannot pass through
/opt/myapp/app/, app.py, requirements.txtroot:myapp0750 / 0640Apps read only their own code
/opt/myapp/venv/root:root0755 (umask 022 default)Dependencies installed by root; outer layer 0750 blocked access by others
/opt/myapp/run.shroot:myapp0750Start wrapper script (Lesson 2 by ExecStart Replaced)
/etc/myapp/, myapp.envroot:myapp0750 / 0640Configuration and Confidential
Before startingConfirm systemctl is-active redis-server is active, sudo ss -ltn 'sport = :5000' No output (module 8's http.server Stopped),python3 -m venv --help Available. It is recommended to take a snapshot first: on the host machine multipass stop linuxlab && multipass snapshot linuxlab --name before-myapp && multipass start linuxlab.
1. Prepare the source code (labadmin's working directory)
 data-l="bash"
2. Create the system user myapp
 data-l="bash"
 class="out" data-l="Expected output (example)"
3. Create the directory, install the code and virtual environment
 data-l="bash"
 class="out" data-l="Expected output (example, excerpt)"

labadmin's own execution of python in the venv is rejected - because /opt/myapp is 0750 root:myapp, labadmin is not in the myapp group and cannot be traversed (path resolution rules of module 3). This is exactly what we want. The dependent minor version is based on PyPI when installed.

4. Configuration file and startup script
 data-l="bash"
 class="out" data-l="Expected output (example)"

set -a Let the variables coming in from the source be exported automatically, so that the gunicorn process can see REDIS_HOST in the environment (Module 2: Shell variables vs environment variables). exec causes the Shell to be replaced by gunicorn (module 1), and SIGTERM is sent directly to gunicorn when stopped.

5. Manually start as myapp (background job)
 data-l="bash"
 class="out" data-l="Expected output (example)"

PPID 6118 is the sudo process (sudo will fork out the command and wait for it); master 6120 forks out two workers. The log file is opened by labadmin's shell (redirection occurs before sudo).

6. Functional acceptance
 data-l="bash"
 class="out" data-l="Expected output (example)"
7. Security acceptance (these operations should fail)
 data-l="bash"
 class="out" data-l="Expected output (example)"
8. Graceful stop and check
 data-l="bash"
 class="out" data-l="Expected output (example)"

We stopped it deliberately: the manually run service will not automatically recover after the terminal is closed or restarted, and the log is only in one file - Lesson 2 will write /etc/systemd/system/myapp.service (User=myapp, EnvironmentFile=/etc/myapp/myapp.env, ExecStart=/opt/myapp/venv/bin/gunicorn …, Restart=on-failure, After=redis-server.service), and give the log to journald.

Acceptance Checklist

Open-ended self-test (6 questions)

1. Why is the venv created by root and the code owner is root instead of chown -R myapp /opt/myapp?

If the application has its own code and dependencies, any remote code execution vulnerability can write malicious code into app.py or site-packages and persist it. Owned by root, myapp is read-only, so that attackers cannot tamper with the code even if they control the process; places that need to be written (caching, uploading) should be given separate directories (such as /var/lib/myapp, Lesson 2 StateDirectory=).

2. What are the consequences of setting myapp.env to 0644? What if it is set to 0600 root:root?

0644: All local users can read the configuration, and Redis passwords and API keys added in the future will be leaked. 0600 root:root: The myapp user cannot read, ./etc/myapp/myapp.env in run.sh will fail (Permission denied), and the application fails to start. 0640 root:myapp is the balance point. In Lesson 2, systemd reads EnvironmentFile as root, so you can consider 0600 root:root.

3. Who does the log file in sudo -u myapp /opt/myapp/run.sh > ~/linuxlab/myapp.log belong to? Why?

Belongs to labadmin. The redirection is opened by labadmin's bash in the forked child process before sudo is executed (module 1); sudo only inherits this opened fd 1 to gunicorn. If you want the log to be written to a protected directory as myapp, you need to redirect it within the myapp command (such as sudo -u myapp sh -c '… > /var/log/myapp/app.log'), or give it to journald.

4. If exec is removed from run.sh, what will be the difference when stopping?

sh will fork gunicorn as a child process and wait as the parent process. pkill -f gunicorn will still hit gunicorn, but if you stop "run.sh's process" by PID and the SIGTERM is sent to sh, sh will not forward the signal (same problem with shell form CMD in the Docker lesson) and gunicorn may continue to run or become orphaned after sh is killed. systemd will kill all processes by cgroup, but the order of graceful stop will be affected.

5. Using the idea of ​​​​readiness review, list what is missing before myapp goes online?

Auto-start at boot and crash restart (systemd), centralized logs and rotation (journald), resource limits (MemoryMax, TasksMax), firewall only opens 5000 for load balancing (lesson 6), TLS termination (reverse proxy), monitoring /healthz and indicators (Prometheus class), Redis Persistence and backup, dependency version locking (pip freeze generates lock files), automated deployment (Ansible/CI).

6. What needs to be changed in the same deployment on Rocky Linux 10?

Package: sudo dnf install python3 valkey (EL10 uses Valkey to replace Redis, service name valkey), and systemctl enable --now valkey (RHEL does not start automatically); python3 -m venv is usually included on EL; SELinux is enforcing, file contexts under /opt/myapp and non-standard port 5000 may require semanage adjustments (lesson 6); firewalld blocks 5000 by default (firewall-cmd --add-port=5000/tcp); the administrator group is wheel.

Final Test

Source and version description

All version facts were verified on 2026-11-17 against ubuntu.com, documentation.ubuntu.com, packages.ubuntu.com, kernel.org, man7.org, distribution official announcements and AWS documentation
Verification date 2026-11-17
TopicVerification ConclusionSource (Accessed 2026-11-17)
Ubuntu LTS and support period26.04 LTS was released on 2026-04-23, with standard security maintenance until 2031-05, and ESM until 2036-05; 24.04 LTS standard support until 2029-05, ESM until 2034-05; 20.04 standard support ended in 2025-05; latest transition version 26.10 (2026-10)Ubuntu release cycle; 26.04 release notes
Component changes in 26.04 relative to 24.04GA kernel 6.8 → 7.0; systemd 255 → 259 (remove cgroup v1, the last version with SysV script compatibility); APT 2.7 → 3.1 (remove apt-key, new solver, history command); Python 3.12 → 3.14; OpenSSH 9.6p1 → 10.2p1 (no DSA); chrony replaces systemd-timesyncd (new install)Summary for LTS users
sudo-rs and rust-coreutilsSince 25.10, sudo is provided by sudo-rs (the original version is sudo.ws), coreutils is provided by uutils; in 26.04, cp, df, mv, rm, true are still from GNU; switch coreutils to use coreutils-from-gnu / coreutils-from-uutils package (do not use update-alternatives); sudo-rs does not support I/O logs, sudoreplay, sudo-ldap, and the prompts are differentUbuntu Server: System utility replacements; From LTS to LTS(Ubuntu Foundations)
26.04 package versionbash 5.3-2ubuntu1; python3 3.14.3; redis-server 5:8.0.5-1ubuntu0.1 (universe, source package redis)packages.ubuntu.com(bash, python3, redis-server, resolute)
deb822 sourcesUbuntu uses /etc/apt/sources.list.d/ubuntu.sources; single-line format is deprecated, "no earlier than 2029" Year" removed; field Types / URIs / Suites / Components / Signed-Bysources.list(5)
Linux Kernelmainline 7.4-rc3(2026-11-15); stable 7.3.4; longterm 6.18, 6.12, 6.6, 6.1, 5.15, 5.10kernel.org
systemd UpstreamLatest release v262.x (GitHub releases marked Latest); used by Ubuntu 26.04 259systemd releases
RHEL seriesRHEL 10.3 and 9.9 were released on 2026-11-11 (kernel 6.12); Rocky Linux 10.2 was released in late 2026-05 (the latest official version at the time of verification); AlmaLinux 10.1 was released on 2025-11-24, 10.3 beta has been released; EL10's dnf is 4.20 (dnf5 has not entered RHEL 10)Red Hat Developer: RHEL 10.3 / 9.9; Rocky 10.2 GA; RHEL-38831 (dnf5 moved out of EL10 build root)
Azure Linux3.0 It is the official version (tdnf); 4.0 will enter public preview in mid-2026. No GA announcement was found during verificationReports of Microsoft Build 2026 announcement (such as Redmondmag); for Lesson 3, please check learn.microsoft.com
Amazon Linux 2023Standard support to 2027-06-30, maintenance period until 2029-06-30; quarterly version, AMI and warehouse version coupling; dnfAL2023 release cadence
Multipasslatest 1.17.1; launch's --cpus (default 1), --memory (default 1G), --disk (default 5G), the image parameter can be codename/alias/version, if omitted, it will be the latest LTS; there is no option to attach additional disks in the official CLI referencemultipass launch; Multipass releases
Permission determination algorithmACL check sequence: owner → named user (∧mask) → Group (any matching entry ∧mask) → other; when mask exists, the group permission bit corresponds to mask; search permissions are required at each level of the path; CAP_DAC_OVERRIDE requires at least one x bit when executed; Linux uses fsuid for permission checkacl(5); path_resolution(7)
Bash expansion and exit codeExpansion order: braces, tildes, argument/variable/arithmetic/command substitution, word splitting, pathnames, dequotes; 126 / 127 / 128+NBash Manual; Exit Status
myappConsistent with Jenkins/GitLab class: Flask + redis + gunicorn, /healthz Return {"status":"ok"}; Depends on flask==3.1.*, redis==5.*, gunicorn==23.*; Port of this course is 5000Jenkins Lesson 1

Video Verification Instructions

This lesson only lists videos passed by YouTube oEmbed (https://www.youtube.com/oembed?url=…&format=json) on 2026-11-17 Verify the title and channel of the video:

oEmbed Only the title and channel were verified, and the content was not viewed segment by segment; the content description in "meta" comes from the title and public information, and may be different from the video details. Most of these videos were recorded before Ubuntu 26.04: sudo-rs prompts, rust-coreutils, deb822 sources, APT 3's new commands, etc. are subject to this lesson. There is no verified video that specifically explains the "whole process of fork/execve" and "ACL determination algorithm". The corresponding content is based on the animation and storyboard of this lesson.

Voice explanation instructions

The "Voice" page uses the built-in Web Speech API of the browser to read the Chinese explanation script (en-US) and English terminology (en-US), and does not rely on the network or external scripts. This courseware cannot embed MP3 or generate video; the explanation draft and storyboard script can be handed over to TTS or video tools to generate audio and video.

Known limitations

  • The experimental commands are not executed in the real environment: There is no Ubuntu 26.04 virtual machine available when this courseware is written. All "expected outputs" are examples, in which PID, UID/GID, IP, timestamp, kernel minor version (such as 7.0.0-15), package revision number, file size, log statistics, and hash are indicative values; the output wording of rust-coreutils and the GNU version may be slightly different.
  • sudo-rs installation path (/usr/lib/cargo/bin/sudo), --version output, rejection wording ("I'm sorry … I'm afraid I can't do that") and sudo -l format are not tested on 26.04; visudo is in sudo-rs Please refer to command -v visudo for the following provision method.
  • Multipass's image alias (26.04 / resolute / lts) is subject to the actual output of multipass find; the official document does not list the specific alias. Multipass does not have a proven "attach second disk" command, so the LVM lab in Lesson 2 uses a loopback device.
  • The distribution name and default systemd settings of Ubuntu 26.04 in WSL2 have not been verified. The courseware requirements are based on wsl --list --online and ps -p 1 -o comm=.
  • The default umask (0002 vs 0022) for ordinary Ubuntu users depends on the combination of pam_umask and USERGROUPS_ENAB. The courseware is subject to the actual output of umask, and the example is written according to 0002.
  • RHEL 10 uses Valkey to replace Redis, and AlmaLinux 10.1 starts with CRB enabled by default. Reference information such as CRB comes from second-hand reports in the release announcement. The rhellab part of Lesson 6 is optional. Please refer to the actual output of dnf info. Unable to confirm whether Azure Linux 4.0 is GA, will be re-verified in Lesson 3.
  • APT 3's apt history-list output column format is schematic; the version number in apt policy comes from packages.ubuntu.com (resolute), and different revisions may be seen depending on the mirror synchronization time.
  • The "Execute a command" animation is based on the public behavior of fork and command search in the bash source code (bash searches for commands in the parent process, handles redirection and command_not_found_handle in the child process) and the simplified implementation of system calls observable by strace, omitting vfork optimization, signal masking, and dynamic link details; the "permission determination" animation is based on acl(5) and path_resolution(7), not included Impact of LSM, mount options, and user namespace. The pipeline simulator uses JavaScript to simulate the semantics of awk/sort/uniq/sed in the browser, covering only the functions used in the example.
  • myapp's Python dependency uses a version range (flask==3.1.*, etc.), and the actual installed minor version depends on the PyPI installed; gunicorn 23 has not been tested on Python 3.14.