Skip to main content
Systems Programming

Linux Commands and the VI Editor

Published: 2026-08-20
Level: postgraduate
Audience: Postgraduate students in Systems Programming

# Linux Commands and the VI Editor

6.1 The wc Command — Counting Lines, Words and Bytes

Hook: Imagine you hand in a worksheet that asks for lines, words, and characters in myfile.doc — and separately you need to answer how many users exist on the whole Linux machine. Both questions are really the same: how do you count items inside a file? The answer is one tiny utility that does nothing but count.

Counting without seeing each item by hand is the problem wc solves. The lecture frames it first as a classroom worksheet (myfile.doc) and then as a live system question about /etc/passwd. That move from toy file to system file shows why counting is not a toy skill.

Intuition — the tally clerk: Think of wc as a clerk at an entry gate with three hand clickers. One clicker ticks on every newline character, one ticks on every whitespace-separated word, one ticks on every byte. The clerk walks the file line by line, never guessing, never estimating. At the end the clerk reports the three totals.

Mapping: clerk = wc process, gate = read loop, clickers = counters for -l, -w, -c, file = queue of lines. Where the analogy breaks: a human clerk might miscount or get tired; wc is byte-exact and counts even empty lines and invisible newline bytes. It also counts bytes, not what a human thinks of as characters, when encodings differ.

Formalize — what wc is and its syntax

wc — short for word count — is a filter that counts lines, words, and bytes in one pass. Formally, for a file F:

  • line = sequence ending in newline \n; -l counts newline characters
  • word = maximal sequence of non-whitespace characters bounded by whitespace; -w counts those tokens
  • byte = single 8-bit unit; -c counts bytes

Syntax:

wc [ -l | -w | -c ] [ file ... ]
  • wc file with no option prints lines words bytes filename in that order.
  • wc -l file prints lines only.
  • wc -w file prints words only.
  • wc -c file prints bytes only.
  • With multiple files, wc also prints a total line. With no filename and data piped in, it reads standard input. Options -l, -w, -c can be combined as wc -lw but the cleanest use is one at a time while learning.

For plain ASCII, bytes equal characters. That is why the lecture says 4241 bytes = 4241 characters for /etc/passwd in this demo; with UTF-8 multi-byte characters the two can diverge.

Worked example — wc on /etc/passwd

Setup: /etc/passwd lives in /etc. Each line holds one user record — name, user ID, group ID and other colon-separated fields — so counting lines counts users.

Live system totals from the demonstration:

  • wc /etc/passwd72 100 4241 /etc/passwd
  • 72 lines
  • 100 words (whitespace-separated tokens; note /etc/passwd uses colons, so many lines are one word)
  • 4241 bytes

Isolated counts:

  • wc -l /etc/passwd72 — answer to "how many users?" = 72. This includes the student account, root, and temporary users added earlier with adduser.
  • wc -w /etc/passwd100
  • wc -c /etc/passwd4241

Sense-check: 72 lines averaging about 59 bytes each gives ~4241 bytes, plausible for colon-separated records. Word count 100 is low because colons do not split words — a line like root:x:0:0:root:/root:/bin/bash is one word to wc, not seven. If words were far larger than lines, you would suspect a delimiter mismatch — that reasoning confirms the numbers hang together.

Worksheet mapping: the same pattern answers myfile.docwc myfile.doc for all three together, then wc -l, -w, -c separately for each sub-question.

Visual intuition: picture the terminal after wc /etc/passwd. Horizontally you see three numeric columns left to right — lines, words, bytes — then the filename. Vertically, wc walks from top of file to bottom, incrementing counters. The line counter jumps only at \n, the word counter jumps when leaving whitespace, the byte counter ticks every character including : and \n. At EOF the three counters freeze and are printed as one row. Adding -l hides the word and byte columns visually — only the first number remains.

Scope and assumptions — when wc means what you think

  • Assumption: newline-terminated lines. wc -l counts newline bytes. A final line without trailing newline is not counted as a line — rare but possible in hand-crafted files.
  • Assumption: word = whitespace-separated. In /etc/passwd colon is not whitespace, so wc -w underreports human-expected fields. For colon fields use cut -d: or awk -F:.
  • Bytes vs characters. -c reports bytes. With ASCII, bytes = characters. With UTF-8 containing multi-byte characters, use wc -m for characters. The lecture uses ASCII, so 4241 bytes equals characters.
  • Binary files. wc will count bytes on a binary, but lines and words are meaningless. Use wc -c only for binaries.
  • Empty or missing files. wc on empty prints 0 0 0. No file or permission denied is an error, not zero.

Pitfalls — what trips beginners

  • Mixing up -c and -m. Remember: -c is bytes, -m is characters. In the exam write "bytes (equals characters for ASCII)".
  • Forgetting that no option prints all three. Students run wc -l and wonder where words and bytes went — they asked to suppress them.
  • Parsing the three numbers in wrong order. Order is always lines, words, bytes. Reading as bytes, lines, words gives the wrong user count.
  • Counting users by words. Each user is one line, not one word. Use wc -l /etc/passwd, not wc -w.

Q: Where do we get user information in a Linux system — what file holds user ID and group ID? A: In /etc/passwd inside the /etc folder. Each line corresponds to one user, so counting lines counts users. Group information is also managed in the system, but the concrete user count used in class is wc -l /etc/passwd.

Q: Where do we get user information in a Linux system — what file holds user ID and group ID? A: In /etc/passwd inside the /etc folder. Each line corresponds to one user entry with username, user ID, group ID and other fields. Because one user equals one line, wc -l /etc/passwd counts users. In the demo that count is 72, including the logged-in student, root, and temporary users created with adduser.

Exam note: Expect a direct question asking for lines, words, and characters separately and together. Know wc with -l (lines), -w (words), -c (bytes) and that plain wc file prints all three in one line. Be ready to quote the demo totals: 72 lines/users, 100 words, 4241 bytes for /etc/passwd style file, and to answer the worksheet myfile.doc the same way.

Recap and bridge: wc is the baseline counting filter: three counters, three options, one combined default. It answers "how many" for lines/records, words/tokens, and bytes. Once you can count, you can triage — next you need to know what kind of file you are counting, which is the job of the file command.

Real-world and domain connection: system administrators use wc -l daily — wc -l /etc/passwd for user audit, wc -l /var/log/syslog for log size, wc -l data.csv to confirm a generated data file has the expected number of records, who | wc -l to count logged-in users, ls | wc -l to count files. In data pipelines, wc -l gates whether to proceed, and wc -c validates file size before commit or upload. Among user utilities introduced in systems programming labs, wc is among the first because counting underpins filtering, sorting, and scripting that follows.

6.1.1 Worked Computation — wc on /etc/passwd

Trace — isolating each count

  • Prompt: Given /etc/passwd with one user per line, report lines, words, bytes separately and together.
  • Step 1 — combined: wc /etc/passwd72 100 4241 /etc/passwd — prints lines words bytes filename.
  • Step 2 — lines only: wc -l /etc/passwd72 — exactly the user count. The professor notes you get what you asked for without parsing the full row.
  • Step 3 — words only: wc -w /etc/passwd100 — shows colon-joined records count as few words.
  • Step 4 — bytes only: wc -c /etc/passwd4241 — total storage in bytes, equals characters here.

Interpretation: 72 users exist at that moment on that machine. The narration emphasizes applying the option that matches the question rather than extracting a field from the three-column output by hand.

Takeaway: wc with -l, -w, -c isolates one counter; without an option you get all three. For /etc/passwd, lines = users, so wc -l is the field answer. Keep the order lines → words → bytes and the byte-equals-character rule for ASCII in mind for the exam.

6.2 The file Command — Identifying What Kind of File You Have

Hook: A file named student.doc looks like a Word document. Is it? On Linux the name can be a lie. One command ignores the name and reads the content to tell you the truth.

Why this matters is immediate: on a server you receive files with no extension, wrong extension, or a name copied from another system. Guessing by name and running cat on a binary or gcc on plain text wastes time and can break a workflow. Knowing the internal format first decides the next step.

Intuition — the lab technician: Think of file as a lab technician who ignores the label on a bottle and runs a quick test on the liquid inside. The label (file name or extension) is hearsay; the test (magic bytes, structure scan) is evidence. The technician reports in plain language: "ASCII text," "C source," "LSB shared object, dynamically linked," or "directory." Where the analogy breaks: the technician does not modify or execute the file — only classifies it — and the test is file-content patterns, not chemical reactions.

Formalize — what file tests and its syntax

A file type is the internal format the system recognizes — text encoding, source language, compiled object, directory, and more. The file utility classifies by inspecting content: magic number at file start, character distribution, and structure.

Syntax:

file <pathname> [ <pathname> ... ]
  • Argument is a pathname; many names can be given at once.
  • Output per argument: pathname: description — one line, human-readable.
  • Classification is content-driven, not extension-driven. A file named .doc containing only ASCII will be reported as ASCII text, and a file named F1 with no extension but containing a compiled binary will be reported as LSB shared object.
  • The description often carries detail after the base type: C source, ASCII text means text that matches C syntax, LSB shared object, dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux ... means a binary built as a position-independent shared object using a dynamic interpreter for a given architecture and version.

Common base reports you must recognize: ASCII text, C source, ASCII text, LSB shared object, dynamically linked, and directory. Directories are file-system objects, not regular files, and file labels them as directory.

Worked checks — one command, many types

The lecture walks file across distinct objects to prove that one command discriminates by content:

  • file /etc/passwd/etc/passwd: ASCII text — plain colon-separated text, as expected for the user database.
  • file output.txtoutput.txt: ASCII text — generic text output, same base type.
  • file fork1.cfork1.c: C source, ASCII text — text but with C markers (#include, ;, braces) recognized as C source.
  • file student.docstudent.doc: ASCII text — despite the .doc name the content in this example is plain ASCII text. The name did not decide; the content did.
  • file F1F1: LSB shared object, dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux ... — not text at all, but a binary built for GNU/Linux, requiring a dynamic linker at run time. The extended detail includes target ABI, version, and linkage — evidence it is an executable shared object, not something you cat or edit directly.
  • file <dirname>dirname: directory — file sees the directory inode type, not file content.

Sense-check: three ASCII-like names all report ASCII but fork1.c adds the C source qualifier and F1 diverges completely to binary. That split is exactly the triage you need before choosing cat vs gcc vs cd/ls.

Trace of use: run file first, read the one-line description, then decide — view (cat, less), compile (gcc), execute (./F1), or enter (cd dirname).

Visual intuition: picture a table with two columns — left is pathname you typed, right is a plain-English label. For text files the right side is short: ASCII text or C source, ASCII text. For a binary the right side stretches long with LSB shared object, dynamically linked, interpreter ... , for GNU/Linux ... — the extra phrase signals architecture and linking. For a directory the right side collapses to a single word: directory. The shape teaches you that length and detail of the description correlate with binary complexity.

Scope and assumptions — when file stays reliable

  • Assumption: content is representative. Very short or empty files may be reported as empty or ASCII text without language tag because there is not enough pattern to classify.
  • Assumption: magic database is present. file relies on the system's magic file (often /usr/share/misc/magic). In minimal containers that database may be trimmed.
  • Scope: description is guidance, not guarantee. ASCII text versus UTF-8 Unicode text or C source distinction is heuristic. Verification with cat or a compiler still matters for critical steps.
  • Directories vs regular files: file on a directory checks file type at the inode level, not content scan, so it will never be "ASCII text" even if the directory name suggests a file.

Pitfalls — what trips beginners

  • Trusting the extension. student.doc being ASCII text surprises students who expect Word format. Remember: on Linux, extension is convention only; file reads bytes.
  • Cat on a binary. Running cat F1 after file F1 reports shared object will dump binary garbage to the terminal. If file says LSB shared object, do not cat it.
  • Forgetting that directories are a type. Beginners run file mydir and expect text. The correct reading is directory — handle with ls/cd, not cat.
  • Over-reading the long binary line. The interpreter ... for GNU/Linux ... detail is version and linker info; you do not need to memorize the full path, just recognize "dynamically linked shared object for Linux" as binary executable family.

Recap and bridge: file <pathname> probes content, not name, and returns a one-line type label. It separates viewable text (ASCII text, C source), runnable binaries (LSB shared object, dynamically linked), and containers (directory). That triage decides the next command. Once you know what a file is, the next useful action is to move or rename it — the job of mv.

Exam note: Know that file inspects content, not extension, and recognize the four canonical outputs from the demo: ASCII text, C source, ASCII text, LSB shared object, dynamically linked, interpreter ... for GNU/Linux ..., and directory. A question that renames student.doc but內容 is ASCII text tests exactly this.

Real-world and domain connection: on production servers and in build directories, file is the first triage in scripts — checking that an artifact is dynamically linked for the correct architecture before deploy, confirming a submission is actually C source before gcc, or rejecting a supposed image that is ASCII text. When extensions are stripped during transfer or logging, file restores ground truth. Among system utilities it is the fast, non-destructive classifier before any destructive or compiling step.

6.2.1 Worked Checks — file on Multiple Types

Trace — same command, different answers

Sequence run and read aloud:

  1. file /etc/passwdASCII text — system text database.
  2. file output.txtASCII text — user text file, same family.
  3. file F1LSB shared object, dynamically linked, interpreter ... , for GNU/Linux ... — binary, not text, needs execution not viewing.
  4. file fork1.cC source, ASCII text — text with C syntax tag, candidate for gcc.
  5. file mydirdirectory — container type.
  6. file student.docASCII text — name suggests Word, content says plain text; trust content.

Decision rule reinforced: extension alone does not decide — content does. The professor stresses that one line from file is enough detail to choose cat vs gcc vs execute vs cd.

Takeaway: file is content-first triage. Memorize the mapping from description to next action: ASCII text → view, C source → compile, LSB shared object → run, directory → list/enter.

6.3 The mv Command — Move and Rename

Hook: You have fork1.c, fork2.c, fork3.c in /OS and need them in /SP — and zombie should have been named zoom all along. How do you relocate and correct names in one command family without leaving a copy behind?

The lecture frames mv as simultaneous move and rename: when the destination is a new name, it is a rename; when the destination is a directory, it is a relocation; in both cases the source disappears.

Intuition — the labeled tray move: Think of mv as sliding labeled trays from one shelf to another. You pick up the tray named zombie and set it down as zoom on the same shelf — that is a rename in place. Or you pick up every tray whose label ends in .c from shelf /OS and carry them to shelf /SP — that is bulk move. There is no photocopy tray left behind, unlike cp which leaves the original. Where the analogy breaks: trays are physical objects that occupy space on both shelves at once during the carry; in the filesystem the directory entry is atomically repointed, and a move within the same filesystem does not duplicate bytes — it changes the name lookup, which is why it is instant even for large files.

Formalize — syntax and two uses

mv — move — renames or moves filesystem objects. It does not copy; after success the source pathname no longer exists.

Syntax forms:

mv source destination        # rename one file or directory
mv source ... directory      # move one or more sources into a directory
  • Rename single file or directory: mv zombie zoom — file zombie becomes zoom in the same directory. Verify with ls. Same form renames a directory.
  • Move a group into a directory: mv /OS/*.* /SP — every file in /OS whose name contains a dot with an extension (*.* = any name, dot, any extension) is moved into /SP. Afterward ls /OS shows them gone; ls /SP shows them present.
  • Filtered move: mv /SP/*.c /OS — only C sources are moved back — fork1.c, fork2.c, fork3.c, zombie.c etc. The pattern *.c is placed at the end to filter by extension. *.* would move everything with a dot; *.c narrows to C files.

Wildcards * and *.* are expanded by the shell before mv sees them: * is any sequence, *.* is name dot extension, *.c is any name ending in .c. The professor highlights that *.c at the end is the correct filter; *.* at the end is not the same as *.c.

Key distinction emphasized repeatedly: cp leaves the original, mv does not. That is a data-loss risk if you move instead of copy by mistake, and a cleanup benefit when you intend to relocate.

Worked examples — wildcards in action

Initial state (verified with ls /OS): files fork1.c, fork2.c, fork3.c, zombie, plus other extension files live in /OS; /SP is the destination.

  1. Bulk move with extension filter: mv /OS/*.* /SP
  • Shell expands /OS/*.* to every pathname in /OS containing a dot.
  • mv moves each into /SP.
  • Check: ls /SP now lists the moved files; ls /OS shows those names gone. The move is literal — sources vanished from /OS.
  1. Rename: mv zombie zoom
  • Single source to new name in same directory.
  • Check: ls shows zombie disappeared, zoom appeared with same content. The inode is the same file under a new name.
  1. Return filtered: mv /SP/*.c /OS
  • Shell expands /SP/*.c to fork1.c, fork2.c, fork3.c, zombie.c etc. in /SP.
  • mv moves only those .c files back to /OS.
  • Check: ls /OS regains the C sources; ls /SP retains only non-.c files (if any). Placing *.c at the end is the filtering pattern a student confirmed correctly.

Sense-check: after the round-trip, the set of .c files ends where it started, but any non-.c files moved in step 1 remain in /SP — which proves *.c filtered rather than *.* moving everything again.

Visual intuition: picture two directory boxes side by side, /OS on the left, /SP on the right, with ls showing file tags inside each. Arrow for mv /OS/*.* /SP sweeps every dotted tag from left box to right box, leaving left nearly empty. Arrow for mv zombie zoom is a short rename loop inside one box — label flips. Arrow for mv /SP/*.c /OS is a selective sweep where only .c-tagged items fly back. The takeaway is that arrow shape is determined by wildcard after the slash.

Scope and assumptions — when mv behaves as described

  • Assumption: destination type matters. If destination is an existing directory, sources are moved into it. If it is a non-existing name, the single source is renamed to it. Confusing these gives "is a directory" errors.
  • Scope: same filesystem is rename of directory entry. Within one filesystem mv is fast pointer update. Across filesystems or devices it must copy then delete, so time and space depend on size.
  • Assumption: wildcard expansion by shell. mv never sees *; the shell expands it first. An empty expansion (no match) behavior depends on shell settings — with default nullglob off, the literal pattern is passed.
  • Scope: permissions. You need write and execute on source directory to remove the entry and on destination directory to create it. Lack of permission fails the move.
  • Scope: no copy retained. There is no backup unless you make one first. This is by design for reorganization and archiving.

Pitfalls — what trips beginners

  • Using mv when you meant cp. The source disappears. If safety is needed, copy first or use cp then verify before removing.
  • Writing mv /OS/*.* /SP as mv /OS/* /SP or mv *.* incorrectly. *.* means name dot extension; plain * includes extensionless files like zombie. Choose the pattern that matches the intended set.
  • Placing wildcard wrong for .c files. mv /SP/*.* /OS would move everything with a dot, not only C sources. The correct filter is mv /SP/*.c /OS with *.c at the end.
  • Overwriting without warning. If a file with the same name exists at destination, default mv overwrites. Use mv -i for interactive prompt when safety matters.
  • Forgetting to verify with ls. The professor checks both directories after each move — adopt that habit to prove the move really happened.

Recap and bridge: mv is move-and-rename by changing directory entries: mv zombie zoom renames, mv /OS/*.* /SP bulk-moves by extension, mv /SP/*.c /OS filters back by *.c. Source is gone, unlike cp. Once files are placed, you need to move yourself among directories — the job of cd, where a single character changes the destination entirely.

Exam note: Know the three patterns demonstrated: mv zombie zoom for rename, mv /OS/*.* /SP to move all with extension, mv /SP/*.c /OS to filter by .c. Remember mv moves, not copies, and that *.c at the end is the testable wildcard placement.

Real-world and domain connection: build and deploy workflows rely on mv — moving compiled .o and .c sources between src, build, and archive, renaming binaries from a.out to service, or rotating logs by moving app.log to app.log.1. In those pipelines, mv within a filesystem provides atomic rename for safe updates (mv new.conf app.conf). The lecture's reorganization demo is the minimal form of that production pattern.

6.3.1 Worked Examples — mv with Wildcards

Trace — verifying each state with ls

  • State 0: ls /OS shows fork1.c fork2.c fork3.c zombie and other dotted files.
  • After mv /OS/*.* /SP: ls /SP lists the moved files; ls /OS shows none of those dotted names remain — some extensionless name may remain if it lacked a dot.
  • After mv zombie zoom: ls shows zoom not zombie — same file, new label.
  • After mv /SP/*.c /OS: ls /SP no longer shows *.c files; ls /OS regains fork1.c fork2.c fork3.c and similar .c files, verified by the professor with ls on both directories. The filter succeeded because *.c at the end selected only C sources.

Takeaway: Wildcard at the end selects. *.* selects any extension, *.c selects only C. Always verify with ls on both source and destination after a move.

6.4 Navigating with cd — Root, Home, Current and Parent

Hook: Four one-character arguments to cd send you to four totally different places. One takes you to the top of the whole filesystem, one to your home, one nowhere at all, and one exactly one level up. Confusing them is the classic exam trap flagged in this lecture.

The lecture treats cdchange directory — not as a minor helper but as absolute navigation: what you type defines where you land regardless of where you started. The professor runs pwd after each cd to prove the landing.

Intuition — floors of a building: Think of the filesystem as a building. / is the ground-floor lobby — one place at the very top (root). ~ is your apartment (home) — wherever you are in the building, cd ~ takes you to your door. . is the room you are already in — cd . is stepping in place. .. is the floor immediately below your room — its parent. ../.. is two floors down to the grandparent. Where the analogy breaks: real buildings have only upward levels; the filesystem is a tree where .. from root stays at root and ~ is per-user, not one fixed floor.

Formalize — four symbols and two composites

cd syntax:

cd [dir]    # dir may be absolute or relative; with no arg, many shells go to home
pwd         # prints where you now are; use after every cd while learning

Symbols:

  • /root — top of filesystem. cd / always goes to /. pwd shows /. Prompt changes to reflect root. Absolute, not relative.
  • ~ (tilde) — home directory of the logged-in user. cd ~ jumps to that home from anywhere. pwd shows /home/<user>. One student guessed neighboring directory — corrected: not neighboring, home.
  • .current directory. cd . keeps you exactly where you are. The professor stresses . is not root and not "current slash."
  • ..parent directory — immediate parent. cd .. goes up one level. Technically write "parent directory" for full marks, though "previous directory" or "one directory back" is understood.

Trick composites dissected live:

  • cd ./.. — current directory ./ then parent .. — net effect is still the parent. cd ./.. and cd .. both take you to the parent, not the grandparent. Writing cd . / .. without the slash is not the same.
  • cd ../.. or cd ../../ — parent of the parent — two .. components separated by /. From the current directory it climbs two levels to the grandparent. The professor makes the class think before answering hurrying leads to answering cd .. when cd ../.. is needed.

Observed variant: cd -- in the demo kept the shell in the current directory with no movement. The professor notes this as a new observation even to them; in this environment it did not act as a standard navigation operator like ~, ., or ...

Worked navigation — pwd proves each landing

Each line is run and checked with pwd:

  • From /home/user/SP, cd // — verify pwd/ — lobby.
  • From /, cd ~/home/user — verify pwd/home/user — apartment; prompt changes.
  • From /home/user, cd . → stays at /home/user — stepping in place, pwd unchanged.
  • From /home/user/SP, cd ../home/user — up one level to parent.
  • From /home/user/SP, cd ../../home — up two levels to grandparent. Writing cd ./.. from /home/user/SP would still give /home/user, not /home, proving ./.. is one level not two.

Sense-check: grandparent requires two .. separated by /; one .. never reaches grandparent even if prefixed with ./.

Visual intuition: picture the pathname as a vertical stack: / at top, then home, then user, then SP at bottom where you stand. cd / jumps to top of stack, cd ~ jumps to the user line regardless of depth, cd . stays on the SP line, cd .. erases SP and lands on user, cd ../.. erases two lines to home. The stack image makes clear why cd ./.. erases only one line (the . erases nothing).

Scope and assumptions — absolute vs relative

  • Assumption: cd / is absolute. It ignores current location. cd / from /home/user/SP and from /tmp land in the same place.
  • Assumption: ~ is per-user. Different users landing with cd ~ arrive in different home paths.
  • Scope: . and .. are directory entries. Every directory physically contains . and .. entries pointing to itself and its parent. That is why cd . is valid and cd .. works from any location; .. from / stays at /.
  • Scope: cd ../.. is two components. The slash separates them. cd .. .. without slash is two arguments, not one path, and fails.

Pitfalls — the classic confusions flagged as exam traps

  • Mixing / with ~. cd / is root, not home. If the question says "where does cd / take me, home?" the answer is no — root with pwd /.
  • Mixing ~ with current. cd ~ is home, not current. It moves even when you already think you are home.
  • Mixing . with /. cd . stays, cd / jumps to top. The two are one character apart but opposite.
  • Writing "previous directory" only. Technically .. is parent directory — write that phrase for full marks.
  • Thinking cd ./.. is grandparent. Net is still parent. Grandparent needs cd ../.. or cd ../../ — two .. components.
  • Forgetting to verify with pwd. Run pwd after each cd while learning; the lecture does so after every move.

Q: cd / — where does it take me, home? A: No. / is root. cd / always goes to root. pwd will show /. . is current directory, / is root — do not conflate the two.

Q: cd ~ — where does it take me? A: To the home directory of the logged-in user, wherever you currently are. After cd ~, pwd shows the user's home path, e.g. /home/<user>. Not a neighboring directory — that guess was corrected in class.

Q: cd . — where does it take me? A: Nowhere. . is current directory, so cd . keeps you in the same directory; pwd is unchanged.

Q: cd .. — where does it take me? A: To the parent directory — the immediate parent. The technically expected term is parent directory (parent-child). Saying previous directory or one directory back conveys the same idea but write parent directory for credit.

Q: cd ./.. (cd dot slash dot dot) — is that grandparent? A: No. cd ./.. (dot slash dot dot) still goes to the parent, not the grandparent — net one level up, not two. cd dot slash dot dot is still parent, not grandparent. Hurrying to answer grandparent with cd ./.. is the flagged mistake.

Q: How to go to the grandparent — parent of the parent directory? A: Use cd ../.. (cd dot dot slash dot dot) or cd ../../ — two parent components separated by slash, i.e. cd dot dot slash dot dot is two .. components separated by slash giving two levels up. The lecture highlights that hurrying leads to the wrong cd .. answer; you must write two .. for two levels to reach the grandparent.

Exam note: This zone is marked simple yet tricky. Expect a question to distinguish cd / = root, cd ~ = home of logged-in user, cd . = current (no move), cd .. = parent (write parent directory), cd ../.. = grandparent. cd ./.. is still parent, not grandparent — anticipate a trick question on exactly that.

Recap and bridge: cd navigation is absolute per symbol: / top, ~ home, . here, .. parent, ../.. grandparent. Master pwd checks to prove landing. With movement mastered, you need comparison tools that tell whether two files are the same — starting with the fastest byte check, cmp.

Real-world and domain connection: every interactive session and every shell script relies on cd to set working directory before ls, cat, gcc, or mv. Deploy scripts cd to /var/app, cd .. for relative cleanup, and cd ~ to return to home. Knowing .. vs ../.. avoids operating on the wrong parent during recursive deletes or builds — a production safety skill, not just exam terminology.

6.4.1 Worked Navigation Sequence

Trace — five moves with pwd truth

From a starting point, run and verify:

  1. /home/user/SPcd // (pwd/)
  2. /cd ~/home/user (prompt changes, pwd confirms home)
  3. /home/usercd . → stays at /home/user (pwd unchanged)
  4. /home/user/SPcd ../home/user (parent)
  5. /home/user/SPcd ../../home (grandparent — two parents up)

The sequence mirrors the live quiz: responses that confused /, ~, ., .., and ../.. are corrected on the spot with pwd evidence.

Takeaway: Navigation symbols are absolute definitions, not guesses. Prove each with pwd and write "parent directory" for .. and "../.. for grandparent" to secure marks.

6.5 cmp — Byte-by-Byte Comparison That Stops at the First Difference

Hook: You backed up results.txt to results1.txt, edited one character on line 5, then edited another line farther down. Will a quick check show both changes or only the first? The fastest comparator has a surprising stop rule.

The lecture calls cmp a developer's quick check: when code, scripts, or configs are backed up and then edited, cmp instantly tells whether the current version still matches the backup and, if not, where the first change appears.

Intuition — the quality checker who stops at the first defect: Think of cmp as an inspector walking two printed copies side by side, comparing character by character with a ruler. At the first mismatch the inspector stops, raises a hand, and says "differ at byte 189, line 5." The inspector does not continue scanning — even if more mismatches exist later, they remain unreported until the first is fixed. Where the analogy breaks: a human might note multiple defects; cmp by design reports only the first to give the fastest possible yes/no with location.

Formalize — what cmp does and its syntax

cmp — compare — compares two files byte by byte and stops at the first mismatch. It reports the location of that mismatch as byte number and line number and says the files differ. If files are identical it prints nothing — silence means sameness. This stopping behavior is deliberate for speed.

Syntax:

cmp file1 file2
  • Two operands only — exactly two files. This is a fixed arity, unlike diff or comm which have options.
  • Output on difference: file1 file2 differ: byte 189, line 5 — byte count from start of file, line number of that byte.
  • Output on identical: no output, exit status 0. That silence is the success signal, not missing output.
  • The command does not care about file type (text vs binary); it compares raw bytes. It also does not care about sorting; any two files can be compared.
  • It does not edit files and does not list all differences — later differences are not highlighted until the first is reconciled, a point the lecture repeats as the core lesson.

Worked demonstration — results.txt vs results1.txt

Setup:

  • cp results.txt results1.txt creates an identical copy.

Step sequence from the live demo:

  1. cmp results.txt results1.txt → no output → files are identical. Silence is success. The professor emphasizes: no message means sameness, not error.
  1. Edit results.txt — change a single character, for example replace a 9 with 3 on line 5 using the editor, save.
  1. cmp results.txt results1.txtresults.txt results1.txt differ: byte 189, line 5 — bytes 1–188 and lines 1–4 are identical; byte 189 on line 5 is the first differing byte. The professor counts lines to show why line 5 is reported even though the terminal only echoes byte and line.
  1. Make a second change farther down, e.g., change another word to execute. Run cmp again → still results.txt results1.txt differ: byte 189, line 5. It still stops at the very first difference; later differences are not listed until the first is fixed. Only after restoring byte 189 to match would a subsequent run reveal the next mismatch.

Sense-check: line 5 appearing means four full lines matched. Byte 189 being inside line 5 is consistent with average line length ~35–45 bytes — four lines ~140–180 bytes plus into line 5 reaches 189.

Developer use highlighted: backup vs current — cmp current.c backup.c answers "has anything changed?" instantly with location of first edit.

Visual intuition: picture two horizontal strips representing the two files, left to right = bytes, row breaks = lines. A highlighter scans left to right; everything up to byte 188 is green (matching). At byte 189 on row 5 the highlighter hits red and stops; the remainder of both strips stays grey — not scanned. The one-line message "byte 189, line 5" is the inspector's hand pointing at that red cell.

Scope and assumptions — what cmp assumes and guarantees

  • Assumption: raw bytes. Differences in line endings (\n vs \r\n), trailing spaces, or invisible characters count as bytes and will trigger a mismatch.
  • Scope: two operands only. cmp is not comm or diff with options; give exactly two pathnames.
  • Scope: no column or diff script output. It reports a single location, not a three-column view or an edit script. For full context use comm or diff.
  • Assumption: silence = identical. In scripts, test exit status or empty output; do not expect a printed "identical" message.

Pitfalls — what trips beginners

  • Expecting a full diff. Many expect cmp to list all changes like diff. It does not — it stops at the first. If you need all differences, use diff or fix first mismatch and rerun.
  • Misreading silence. No output means identical, not "command failed." Students who see nothing think it did not run — check exit status or test with a known difference.
  • Confusing byte number with line number. byte 189, line 5 gives both; byte is absolute from start, line is line count. They are not the same unit.
  • Running cmp on unsorted vs sorted expectation. Sorting is irrelevant to cmp — it compares raw bytes. Sorting matters for comm, not here.
  • Trying three files. cmp a b c is an error. Use comm or diff workflows for multi-file comparison.

Exam note: Know that cmp stops at first mismatch and reports byte 189, line 5 style, and that identical files give no output. Be ready to interpret that message and to state that a second, later change will not appear until the first is fixed. Remember it takes two operands only and is a byte-compare, not a line-script tool.

Recap and bridge: cmp is the fastest sameness test: silence is identical, one line pinpoints the first byte and line that differ, and it never looks beyond that point. When you need to see what is unique versus shared across two sets, not just where the first byte diverges, you need the three-column view of comm.

Real-world and domain connection: build and deploy checks use cmp to verify that a deployed binary matches the built artifact, that a restored config is byte-identical to the known-good backup, or that a copy operation succeeded before deeper comparison. Continuous integration often runs cmp as a fast gate before expensive diff or checksum steps. Its developer-oriented speed is why the lecture labels it a developer's tool for current vs backup validation.

6.5.1 Worked Computation — cmp on results.txt

Trace — proving the stop rule

  • Setup: results.txt copied to results1.txt → identical pair. cmp silently succeeds.
  • First edit — single byte change on line 5: cmp results.txt results1.txtdiffer: byte 189, line 5 — first mismatch located.
  • Second edit — additional change later in file: cmp still reports differ: byte 189, line 5 — proves cmp never scans beyond the first difference until that difference is fixed. Only after reconciling byte 189 would a rerun expose the later execute change.

This trace is the exam-defining property: first mismatch only, not a summary of all mismatches.

Takeaway: cmp file1 file2 is a binary decision with a location pointer: empty means same, byte N, line M means first difference there. For all-changes context, switch to diff or comm.

6.6 comm — Three Columns for Two Sorted Files

Hook: You have two lists of numbers and need to know what is only in list one, only in list two, and what they share — at once, in one view, with the ability to hide any column. One command does that, but only if the lists are sorted and you read column-wise, not row-wise.

comm — short for common — is the set-operation viewer. The lecture positions it as not a generic diff: it shows membership, not edit script, and it works on sorted input only.

Intuition — three buckets on a table: Think of comm as sorting two decks of cards, laying them side by side, and dropping each card into one of three buckets: left bucket = only in deck one, middle bucket = only in deck two, right bucket = in both decks. Buckets are columns: column 1 = unique to first file, column 2 = unique to second, column 3 = common to both. Where the analogy breaks: real buckets hold physical cards; comm columns are text offsets with TAB leading — an empty left bucket looks like no column at all, which confuses first-time readers who expect a visible empty box.

Formalize — syntax, columns, suppression, and sorted requirement

Syntax and columns:

comm [ -1 ] [ -2 ] [ -3 ] file1 file2
  • Exactly two sorted files. A third operand is rejected — comm file1 file2 file3 → error. Column definition only has two uniques and one common, so two files are the domain by design.
  • Column 1: lines unique to file1, starting at column edge.
  • Column 2: lines unique to file2, starting after one TAB offset.
  • Column 3: lines common to both, starting after two TAB offsets.

Suppression options hide a column, not elsewhere:

  • -1 suppresses column 1 (unique to file1 disappears).
  • -2 suppresses column 2.
  • -3 suppresses column 3 (common disappears, leaving only differences).
  • Combinations: -12 shows only common lines; -13 shows only unique to file2; -23 shows only unique to file1; -123 would hide everything. "Suppress" means not displayed.

Sorted requirement: input files must be sorted lexically (or numerically with sort -n before). Without sorting, comm still runs but column alignment appears wrong because the algorithm assumes ordered merges. The worksheet 4.5 files that were not sorted or were created with touch versus cat redirection produced that "looks wrong" effect — yet the command was correct, the input order was not.

Empty column cue: if a file has nothing unique, its column is empty — output starts with a TAB offset rather than text. Empty first column is not an error; it means nothing is unique in file1.

Worked examples — from results to num1/num2 to column suppression

A. After editing results.txt vs results1.txt:

One line changed. comm results.txt results1.txt shows the changed line in column 1 (unique to first), the original line in column 2 (unique to second), and the remaining four unchanged lines in column 3. Reading column-wise gives two uniques and one common.

B. Clean numeric demo — num1.txt vs num2.txt:

Create num1.txt with 1 2 3 4 5 (one per line) and num2.txt with a shifted set, e.g. 3 4 5 6 7:

  • comm num1.txt num2.txt prints:
  • Column 1: 1 2 — unique to first
  • Column 2: 6 7 — unique to second
  • Column 3: 3 4 5 — common to both

That matches the definition exactly. Variation in lecture: some walkthroughs use num1.txt with 1 2 3 and num2.txt with 3 4 5 — then column 1 is 1 2, column 2 is 4 5, column 3 is 3. Pattern is the same.

C. Suppression:

  • comm -12 num1.txt num2.txt → only column 3 remains → 3 4 5 — useful to extract common entries.
  • comm -13 num1.txt num2.txt → only column 2 → 6 7 — what is only in second.
  • comm -23 num1.txt num2.txt → only column 1 → 1 2 — what is only in first.
  • comm -3 num1.txt num2.txt → columns 1 and 2 → 1 2 and 6 7 without common — difference view.

D. Only two operands:

  • cp num1.txt num3.txt then comm num1.txt num2.txt num3.txt → error: only two arguments permitted. The professor intentionally tries three files to prove comm can only find common between two files because its column definition only has two uniques and one common.

Sense-check: totals add — unique1 count + unique2 count + common count = unique lines across union. 2 + 2 + 3 = 7 distinct values from 1 to 7.

Visual intuition: picture a wide page with three vertical lanes separated by faint TAB guides. Lane 1 left aligns 1 and 2. Lane 2 is indented one tab and shows 6 7. Lane 3 is indented two tabs and shows 3 4 5 centered. When column 1 is empty, lane 1 is blank white space and the eye lands on lane 2 first — that blankness is data, not a misalignment. Using comm -12 collapses lanes 1 and 2, leaving only the central common lane.

Scope and assumptions — sorted and file creation matters

  • Assumption: sorted input. For numeric files use sort -n first; for text use sort. Unsorted input yields technically correct but misleading columns because the merge algorithm assumes order. The lecture enlarges the terminal and walks columns left to right to prove correct output for properly created sorted files.
  • Assumption: consistent file creation. Worksheet files created with touch then cat > versus both via cat can mislead expectations: touch creates an empty file entry that followed by append may affect ordering perception. Create both files the same way with sorted content.
  • Scope: suppression is display filter. -1 does not delete data; it hides column 1 from view. Piping comm -12 extracts commons.

Pitfalls — what trips beginners

  • Reading row-wise not column-wise. The empty first column case fools students who expect common first then unique. Rule: column number is position, not row sequence. Look at TAB offsets.
  • Confusing empty column with error. Empty column 1 means nothing unique in file1 — textbook case first.txt=First line vs second.txt=First line+Second line → column 1 empty, column 2 Second line, column 3 First line.
  • Supplying three files. comm accepts only two operands — third is rejected. To compare three sets, run pairwise comm or combine with other tools.
  • Forgetting sorted prerequisite. Running comm on unsorted lists and wondering why columns interleave is the top failure; sort first.
  • Mixing up -12 vs -23 meaning. -12 shows only common (suppress 1 and 2), -23 shows only unique to file1. Memorize: number suppressed is the column hidden.

Q: I ran comm example1.txt example2.txt where example1.txt has first line and example2.txt has first line and second line. I expected common first, then unique second, but I got first line and second line side by side differently. Example1 was created with touch then cat > for the second. Why does it look wrong? A: Look column-wise, not row-wise. Column 1 is unique to first — here empty because the first file has nothing unique; column 1 is blank at the left edge. Column 2 starts with an offset and shows Second line — unique to second file. Column 3 shows First line — common to both. The first column being empty is not an error; it means nothing is unique in file1. Create both files the same way with sorted content using cat and comm will align as defined. When files were created with touch the empty file history can misalign expectations, but the three-column rule still holds. The professor recreated clean files: first.txt with First line, second.txt with First line and Second line via cat, then comm first.txt second.txt yielded exactly empty column 1, Second line in column 2, First line in column 3 — exactly as defined.

Q: Does cd -- have any significance? I saw it do nothing. A: In this environment cd -- simply kept you in the current directory — no movement observed. It is not a standard navigation operator like ~, . or .. in this context. This question is handled here because it was asked during the comm sequence, but the answer is about cd.

Exam note: Know the three-column model (unique file1, unique file2, common), that comm requires sorted files and only two operands (third rejected), and that suppression with -1, -2, -3 hides that column — combinations like -12 show only common. Be ready to read output column-wise and to explain an empty first column as "nothing unique in file1."

Recap and bridge: comm is the membership lens: two sorted inputs → three lanes of uniques and common, with flags to isolate any lane. When you need an edit recipe rather than membership — which lines to add, delete, or change to make one file match the other — you need the editing script of diff.

Real-world and domain connection: comm reconciles two sorted lists — for example, two user lists from different systems, two sorted inventory dumps, or file snapshots in system administration (as shown later with file.info1 vs file.info2). comm -12 extracts intersection, comm -23 extracts only-in-first for removal, comm -13 only-in-second for addition. Because it is set-based, it is used in pipelines where sort precedes comm and the result feeds provisioning or cleanup.

6.6.1 Student Q&A — The Empty First Column Confusion

Trace — empty column is information

Given first.txt = First line and second.txt = First line + Second line:

  • comm first.txt second.txt yields (visual with TAB markers):
  • Second line — column 2 (one TAB)
  • First line — column 3 (two TABs)
  • Column 1 is empty — no line exclusive to first.txt.

Reading row-wise suggests "common first, unique second" in one column; reading column-wise reveals the correct partition: common First line is in lane 3, difference Second line in lane 2. The lecture recreates both files cleanly via cat to show this.

Takeaway: Empty column is an answer, not a bug. Always parse comm output by lane (TAB offset), not by print order. Sort first, read column-wise, use -1/-2/-3 to isolate what you need.

6.7 diff — Line-by-Line Difference and the Editing Script

Hook: Imagine two files that are almost the same: one has one line, the other has two. Can a command tell you exactly which line to add or delete to make the first file identical to the second — and flip that advice when you swap the filenames? That reversible recipe is diff.

The professor jokes that diff is "difficult" at first because its notation is compact, not because the idea is. diff compares two files line by line and suggests which lines in the first must be added, deleted, or changed to make the two files identical. It never modifies files itself — it only prints the editing script you would apply, often with the VI editor.

Intuition — the editor's red pen: Think of diff as a teacher marking up draft A to match draft B. Marks say "add this line from B after line 1," "delete line 2 from A," or "change line 3 to match." Arrows show source: < means a line from the first file, > from the second, --- separates a change block. Swapping the drafts swaps the marks: what was "add" becomes "delete." Where the analogy breaks: a teacher might rephrase; diff is literal line identity — whole lines are added, deleted, or changed, not words within a line.

Formalize — notation, arrows, and operand order

diff syntax:

diff file1 file2    # script to make file1 identical to file2

Notation line like n a m, n d m, n c m, or ranges n,m a p,q:

  • a is add — a line from the second file must be added to the first.
  • d is delete — a line from the first file must be deleted.
  • c is change — a line must be altered to match.
  • Numbers on the left of the letter are line numbers in the first file; numbers on the right are line numbers in the second file.
  • Body of output uses < for the first file, > for the second, with --- separating change blocks.

Critical rule: operand order matters. diff fileA fileB answers how to make fileA identical to fileB. diff fileB fileA gives the inverse script (adds become deletes). The lecture repeats this inversion as testable.

Examples of primitive lines:

  • 1a2 — after line 1 in first file, add line 2 from second file.
  • 2d1 — delete line 2 from first operand; position corresponds to line 1 in second.
  • 1,2d0 — delete lines 1 and 2 in first file; 0 indicates no corresponding line in second at that position.
  • 3a2,3 — after line 3 in first file, add lines 2 and 3 from second file.
  • 5c5 — change line 5 in first to match line 5 in second; body shows < old then --- then > new.

This compact range-letter-range encoding is what the exam expects you to parse: left numbers = first file, letter = operation, right numbers = second file, body = which lines participate.

Worked example — one line vs two lines (the 1a2 / 2d1 core)

Setup: one.txt contains First line. two.txt contains First line and Second line.

Case 1 — diff one.txt two.txt = make one.txt identical to two.txt:

  • Output: 1a2 followed by > Second line
  • Reading: after line 1 in first file (First line), add line 2 from second file (Second line). Body > confirms source is second file.

Case 2 — diff two.txt one.txt = make two.txt (two lines) identical to one.txt (one line):

  • Output: 2d1 followed by < Second line
  • Reading: delete line 2 in first operand (Second line) at position corresponding to line 1 in second operand to make them identical. Body < confirms source deleted is from first file.

Classroom correction highlighted: one student guessed 1a0 meaning add after line 1 at position zero. Professor corrected to 1a2 because the source to add is line 2 of the second file, not line zero. The distinction between zero and the actual line number is emphasized — 0 appears only as in 1,2d0 where deleted lines have no counterpart, not as a generic add source.

Renamed contents to avoid "first line / second line" wording confusion:

  • first.txtTwinkle Twinkle
  • second.txtTwinkle Twinkle plus Little star on second line.
  • diff first.txt second.txt1a2 with body > Little star — add Little star from second file after line 1 of first file.
  • diff second.txt first.txt2d1 with body < Little star — delete line 2 from first operand.

Students are asked to predict before showing output; several predictions of 1a0 are corrected to 1a2 on the spot — that correction is the exam lesson on reading the right-side line number as the source line.

Worked example — num1 vs num2 with ranges

Setup: num1.txt has 1, 2, 3 on three lines. num2.txt has 3, 4, 5 on three lines. Goal: make num1 identical to num2 → remove 1 and 2, keep 3, add 4 and 5.

diff num1.txt num2.txt yields two hunks:

  • 1,2d0 — lines 1 and 2 in the first file should be deleted, with 0 indicating no corresponding line in the second file at that position. Body shows:
  < 1
  < 2
  • 3a2,3 — after line 3 in the first file, add lines 2 and 3 from the second file. Body shows:
  > 4
  > 5

Lines 2 and 3 of second file are 4 and 5. If you apply delete 1,2 and add 4,5, the files become identical.

Narration cue from lecture: left side is first file line numbers, right side second file line numbers, letter is operation, displayed block tells which lines participate. The 0 in 1,2d0 signals deletion that has no anchor in the second file.

Sense-check: 1 2 unique to first are removed, 4 5 unique to second are added, 3 common remains — matches comm intuition but diff expresses it as edit operations, not columns.

Visual intuition: picture two columns of lined paper side by side, first file left, second file right. 1a2 is an arrow from right line 2 into the gap after left line 1 — an insertion. 2d1 is a cross-out on left line 2 with no arrow to the right. 1,2d0 is a bracket crossing out two lines on the left with no right counterpart. 3a2,3 is a bracket arrow inserting two lines from the right after left line 3. The > and < in the body are arrowheads confirming direction.

Scope and assumptions — what diff does and does not do

  • Assumption: line-oriented. diff compares whole lines including newline. A trailing newline difference makes otherwise identical last lines differ.
  • Scope: script not edit. diff never modifies files. You must apply adds/deletes/changes manually, for example with the VI editor, or via patch.
  • Scope: default output is normal diff. The lecture uses normal format (n a m with </>). Other formats (-u unified, -c context) exist but the exam targets normal a/d/c with < > ---.
  • Assumption: left is source, right is target. diff A B plans to change A to match B. Remember direction when interpreting 1a2 vs 2d1.

Pitfalls — what trips beginners

  • Guessing 1a0 instead of 1a2. 0 appears only with delete-to-zero (1,2d0), not as add source. Add source is actual line number in second file — 2 or 2,3.
  • Forgetting operand order inversion. diff A B and diff B A give inverse scripts. Swapping operands flips a to d. If question asks "make fileA identical to fileB," start with fileA first.
  • Reading < vs > backwards. < is first file, > is second. < Second line under 2d1 means delete that line from first.
  • Thinking diff edits automatically. A student asked this directly — answer: never. It only suggests edits; you must edit.
  • Mixing comm columns with diff hunks. comm suppresses columns with -1 etc.; diff hunks are not column suppression — different tool, different model.

Q: Does diff try to make changes as it is in the second file automatically? A: No. diff never modifies files. It only suggests: do these adds, deletes, or changes, then the files will be identical. You must edit manually — for example with the VI editor — to apply the suggested changes. The recipe is read, not executed, by diff.

Exam note: Diff notation a add, d delete, c change and the line-number format 1a2, 2d1, 1,2d0, 3a2,3 is testable. Know that left numbers are first file lines, right numbers are second file lines, that 2d1 deletes line 2 from first, 1a2 adds line 2 from second, and that swapping operands inverts the script. Body < is first file, > is second, --- separates change blocks.

Recap and bridge: diff is the editing script complement to cmp and comm: cmp says where the first byte diverges and stops, comm shows membership in three columns, diff says which lines to add, delete, or change — with reversible direction — to make one file match the other without touching the files. With file comparison complete, the next system lens is live process state via top and ps.

Real-world and domain connection: developers use diff to see code changes between versions, to review patches before commit, and to suggest what to change in a configuration file to match a known-good template. In version control, diff underlies git diff and patch -p1. System administrators diff current vs backup configs to generate the exact adds/deletes needed to reconcile drift — precisely the lecture's "make fileA identical to fileB" framing.

6.7.1 Worked Example — One Line vs Two Lines

Trace — predicting before running

Interactive guesses in class:

  • Predict diff second.txt first.txt where second.txt is two lines, first.txt one line → guess 2d1 with < Second line — correct. It says delete line 2 from longer first operand.
  • Reverse: diff first.txt second.txt → many guessed 1a0 — corrected to 1a2 with > Second line — add line 2 from second file after line 1. The correction teaches that the number after a is the source line in the second file, not zero.

With Twinkle Twinkle / Little star wording the same hunks appear as 1a2 > Little star and 2d1 < Little star, confirming content does not change notation.

6.7.2 Worked Example — num1 vs num2 with Ranges

Trace — two hunks, full interpretation

  • num1.txt: 1,2,3 — num2.txt: 3,4,5 — want num1num2
  • Hunk 1: 1,2d0 + < 1 + < 2 — lines 1–2 have no counterpart in second file (0), so delete them.
  • Hunk 2: 3a2,3 + > 4 + > 5 — after line 3 of first, insert lines 2–3 of second (4,5).

Applying both hunks yields 3,4,5num2. The professor narrates each number: left side first file, right side second file, letter operation, body participants. This is the template for reading any range diff.

6.7.3 Clarification — diff Does Not Edit

Clarification — script vs action

diff is read-only suggestion. To enact 1a2 > Little star, open first.txt in the VI editor and insert Little star after line 1. diff will not do it for you. That separation of diagnosis from treatment is why diff output is called a script and why composition with patch or manual editing is the next step.

Takeaway: Master reading hunks as sentences: "left lines operation right lines — with body lines < from first or > from second." Then you can predict diff output before running it, including range forms 1,2d0 and 3a2,3.

6.8 top and ps — Viewing Processes in Real Time

Hook: Three students in the room type top at the same time. How many top rows appear — one or three? The answer reveals whether the view is per-user or system-wide and why system administrators live in top.

A process is a running program instance — a program in execution with its own memory, CPU time, and owner. Two commands view processes in complementary ways.

Intuition — live camera vs snapshot photo: Think of top as a live security camera feed and ps as a still photograph. The camera (top) refreshes continuously, showing CPU %, memory, sleeping vs running, and every process owned by every user, updating as students start or stop top. The photo (ps alone) captures only your processes at one instant; ps aux widens the lens to a system-wide photo matching top's scope but freezes time. Where the analogy breaks: a camera shows motion; top also computes summary statistics like total tasks, CPU utilization %, and memory totals that a photo would not aggregate.

Formalize — what top and ps show and their syntax

top — real-time system-wide view, interactive:

top        # starts live view; press q to quit

Screen includes:

  • Process list with columns for user, command, PID, CPU %, memory %. In the demo three to five users running top each appear as a separate row owned by different users including root and student accounts. sshd also appears as a persistent daemon.
  • Summary header: total number of tasks, how many are sleeping, percentage of CPU utilized, total memory, how much is free, how much is used, and buffer/cache usage.

The professor points out that the count of top rows grows as more students type top — direct proof the view is system-wide, not per-user. To exit, press q. The view is interactive until you quit; it sorts by CPU by default and refreshes every few seconds.

ps — snapshot, scope depends on options:

ps         # snapshot for this user only
ps aux     # snapshot for all users, similar coverage to top but frozen
  • ps alone lists processes for the current user.
  • ps aux — options often written as ps aux or verbally PSAUX — lists all processes of the system, similar coverage to top but as a one-time snapshot rather than a live view. a = all users, u = user-oriented format, x = include processes without a controlling terminal (daemons). The professor runs ps aux to demonstrate the all-process list.

Core distinction: top is real-time continuous; ps is instant snapshot. Both can show system-wide processes, but only top updates live as three to five users start and stop top.

Worked demo — seeing the system breathe

Steps observed in class:

  1. One student runs top → process table shows that user's top plus sshd and system tasks.
  2. Two more students type top on other terminals → top list now shows three top rows, each owned by a different user account. The increment proves system-wide scope.
  3. Header reads: tasks total (e.g., ~120), sleeping (e.g., ~115), CPU % utilized, memory total / free / used / buffer-cache. Those numbers explain load at a glance.
  4. Press q in top → live view exits, returns to shell prompt.
  5. Immediately run ps aux → static list shows the same sshd and user processes, but the top rows from students who quit are gone. The names overlap with top's names, but the view does not auto-refresh — it is a frozen dump.

Sense-check: interactive top rows that appear and disappear with student actions confirm liveness; ps aux rows that match names but not timing confirm snapshot equivalence of scope without refresh.

Visual intuition: picture a dashboard at the top of the screen — four gauges: tasks total, sleeping count, CPU % bar, memory bars for total/free/used and buffers/cache. Below the gauges is a table: columns user | PID | %CPU | %MEM | command. As each student starts top, a new row blinks in; as they press q, the row blinks out. ps aux is the same table printed on paper — same columns, same names, but the gauges are absent and the paper never updates.

Scope and assumptions — scope vs time

  • Assumption: top is system-wide by default. Some configurations filter to user, but default and the lecture's demo are system-wide.
  • Assumption: ps without aux is user-limited. Beginners who run ps and see few rows think few processes exist; add aux for the full system picture.
  • Scope: interactive vs scriptable. top is for interactive monitoring (needs q to exit); ps aux is for scripts that need a static dump piped to grep or wc.
  • Scope: header detail is distribution-dependent. Exact placement of memory vs swap vs buffer/cached lines varies, but the presence of tasks, sleeping, CPU %, and memory gauges is constant.

Pitfalls — what trips beginners

  • Forgetting to quit with q. top fills the terminal and seems stuck; the fix is simply q, not Ctrl+C. Students who force-close lose the header reading.
  • Mixing ps vs ps aux. Running ps and concluding "no sshd is running" is wrong — sshd appears with ps aux but not plain ps unless it is your process.
  • Thinking top rows per user mean multiple daemons. Three top rows are three invocations of the top program itself by three users, not three system daemons — the lecture uses this to prove real-time system-wide listing.
  • Treating the live numbers as fixed. CPU % and free memory in top jitter every refresh; do not report them as constants. For a stable number for a report, use a ps aux snapshot or average.

Exam note: Know how to quit top (q), what top shows (tasks total, sleeping, CPU %, memory total/free/used and buffer/cache, plus user/command list including top per user and sshd), and the contrast that top is real-time while ps is a snapshot — ps alone is current user, ps aux is all processes. Be ready to explain why more top rows appear as more students run it.

Recap and bridge: top is the live monitor — real-time, system-wide, interactive with q to exit; ps aux is the frozen equivalent. Together they let an administrator spot runaway CPU, check memory pressure, or confirm daemons like sshd are alive. Leaving process monitoring, the next system skill is editing files to act on what you see — the visual editor vi.

Real-world and domain connection: data-center and cloud administrators keep top (and its modern successor htop) open to spot runaway CPU consumers, confirm that sshd, nginx, or database daemons are alive, and decide whether to restart or scale. ps aux | grep sshd or ps aux | wc -l is scripting form — count processes, check ownership, trigger alerts. The lecture's observation that multiple top rows appear per user is the smallest illustration of multi-tenant process isolation on a shared Linux host.

6.8.1 Snapshot vs Live — ps and top Compared

Trace — same names, different behavior

Run top then press q, then immediately run ps aux:

  • top refreshes: CPU % jitters, tasks count ticks, three to five top rows appear as three to five users invoke it.
  • ps aux prints: same process names (top at that instant, sshd, shells) but one view only. Only top updates live as users start and stop top.

Teaching point: coverage (all processes) is similar between top and ps aux, but temporal mode (continuous vs frozen) is the discriminator. A question asking "which shows live CPU and sleeping counts updating?" answer: top.

Takeaway: For scripts, use ps aux; for interactive watching, use top and quit with q. Scope (aux vs plain) controls which users you see; mode (top vs ps) controls whether the view lives or freezes.

6.9 The VI Editor — From Line Editing to Full-Screen Visual Editing

Hook: Imagine an editor where typing h j k l does not insert letters but moves the cursor, x deletes a character, ~ flips case, and every line you type lives only on screen until you explicitly write it to disk. That editor still dominates servers where no mouse exists — and mastering its modes is the fastest way to edit over SSH.

An editor is software to insert, remove, and change text in documents. On Linux many editors exist — Notepad and Word on Windows are analogous — but on Linux the lineage matters historically and practically, and the lecture traces it.

Intuition — from one-line peephole to full-screen canvas: Think of ed as a peephole where you see and edit only one line at a time. vivisual interface — opens the wall to a full-screen canvas where you see the whole file and move freely. vimvi improved — is the same canvas with color, highlighting, and more commands, yet vi and vim both start the improved engine on modern systems (vim even announces VI improved). Where the analogy breaks: a physical canvas is always visible; vi hides typed text until you enter insert mode — otherwise keys are movement or commands, not ink.

Second intuition — backend bookkeeping: Think of vi's backend as a grid of cubbies. Options: a two-dimensional array of characters mapping to the screen rows and columns, or a linked list, doubly linked list, or a link matrix — nodes linked in rows and columns so insertion and deletion rewire pointers rather than shifting an array. The trickiest part, as the professor notes, is manipulating that backend, not just displaying characters.

Professor analogy — the preacher story: A preacher asks a hall whether they know what he will preach. If they say no, he leaves saying they would not understand. If yes, he leaves saying they already know. When they split yes and no, he says those who know should tell those who do not and leaves again. The point: whether you know vi or not, the teaching will still happen — failure is a stepping stone, but failing without trying does not help. The joke maps to editor learning: some already know vi, some do not, but all must try hands-on whether right or wrong.

Purpose — why vi persists

Very first Linux editor was ed, called a line editor because you could edit a single line at a time and nothing more. Then came vi, visual, full-screen, letting you see and edit the whole file at once. vim is literally vi improved — modern systems map vi to vim, so typing vi and vim both start the improved version, and vim announces VI improved on startup.

Hardcore programmers stay with vi even today when many editors including Emacs exist; some will not even move to vim improved and remain on vi because once mastered all editing is at the fingertips with no mouse, no dragging, no clicking. Fingers move like rapid fire to insert, delete, copy, and paste. When speed is needed over SSH where graphical editors are unavailable, that keyboard-only workflow is fastest. That is why vi persists.

Related context from class: the 22–23 years ago engineering story — a system software course covering assemblers, interpreters, linkers, loaders, and editors — assigned building an editor in C (Turbo C for Windows was common, some built for Linux, one student built the whole editor in assembly using BIOS and DOS functions for entering, deleting, and reading strings). Backend choices included 2D array, linked list, doubly linked, or link matrix. Students are asked if they have had a similar assignment — some did file create and paragraph insert/delete in system programming lab, though later curricula diluted it.

Worksheet for this chapter is 4.7: create a file named practice, enter the given details, write to file, then close. Observations after each command must be noted — that hands-on is the assessment of vi mastery.

Modes — the triad you must track

vi works in three interacting modes, shown by visual cues:

  • Command mode — initial state and the mode you return to with Esc. Here keys are commands, not text. Cursor movement keys work here, and colon commands are initiated from here. Bottom line shows filename with 5L, 41C style (lines, characters) and no INSERT.
  • Insert mode — where typed characters actually enter the buffer and appear on screen. Entered by pressing i or a or o. Screen indicates INSERT when active; tildes disappear as you type.
  • Command-line mode — entered from command mode by typing : which moves the cursor to the bottom line — the command line at the very bottom of the screen. Here you give file-level commands like w, w <filename>, q, q!, wq, x.

Movement between modes:

  1. Start vi practice → command mode.
  2. Press i or a or o → insert mode (screen shows INSERT).
  3. Press Esc → back to command mode.
  4. From command mode press : → command-line mode (cursor goes to bottom line prompt).
  5. After executing (w, q, etc.) or pressing Esc → back to command mode.

The professor tests the class: with sample.c showing 5L, 41C at bottom, is this insert mode? Answer: no, it is command mode — insert would show INSERT. After pressing i it shows insert. After Esc it leaves insert. After : it is command-line inviting w or wq. Students who answer insert are corrected with bottom-line evidence. Whether right or wrong does not matter — you must try to identify mode from visual cues, not guess.

Worked example — starting vi and the initial screen

Command to start:

  • vi practice or vim practice — with filename you intend to create.
  • Also vim alone then write later with a name.

What you see at start is command mode, not insert:

  • Tildes ~ fill lines where text will go — each ~ marks an empty line beyond file content.
  • Bottom line shows filename you gave and New File if it does not exist.
  • Bottom right shows cursor coordinates and page. At empty start it shows 0,0 meaning first column, first row, page 1/1. As you move, page numbers like 1/1 and column numbers update.
  • If you try arrow keys or type letters like J, Q, C, D, P, U at this stage, nothing inserts. P would be paste, U undo — but without text they do nothing. Typing h, j, k, l also does nothing visible until you understand modes.

The professor deliberately types random letters to prove not every key inserts — only i, a, o switch you to insert.

Extensions: vi does not require an extension; vi practice without .c or .txt works. But if you give .c, vim provides color highlighting — keywords and control structures appear in different colors because vim knows C format. That highlighting is a cue you are editing a C source, not generic text.

Worked example — i versus a versus o

To place characters you must be in insert mode via:

  • iinsert at cursor position. Cursor stays where it was; next typed character appears at that cursor cell, pushing existing text right.
  • aappend — moves cursor one column to the right first, then inserts. You append after the cursor rather than at it.
  • oopen a new line. Regardless of where you are mid-line, o creates a fresh line below and places cursor at its beginning in insert mode.

Demonstration on a line ending at column 17, with careful column tracking:

  • Press i → shows INSERT with cursor still at 17; typing inserts exactly there.
  • Press Esc → command mode → press a → shows INSERT but cursor has moved to 18 — one column beyond — so typing appends after the original cursor char.
  • From mid-line, press o → immediately leaves that line and starts a new empty line below at column 0 in insert mode, even though cursor was mid-line before.

Example typed verbally as hash include stdio.h appears as #include <stdio.h> then void main() lines. Real-world: knowing i versus a avoids overwriting the character under cursor versus inserting beside it — a common frustration when fixing a typo mid-line. Worksheet explores A capital variants; core testable point is i at versus a after vs o new line below.

Visual intuition: picture the screen with ~ rows like empty ruled lines and a status bar at bottom showing filename, New File, 0,0, 1/1. Press i and INSERT lights up mid-bar while tildes evaporate as you type lines. Press Esc and INSERT vanishes, cursor is a block for commands. Press : and a colon prompt appears at the very last line — that line is the command line where w/q live. The one-column shift of a vs i is visible as cursor stepping right before ink appears; o is a carriage return that drops you to a fresh ruled line.

Scope and assumptions — buffer vs file and mode discipline

  • Assumption: what you type lives in buffer first, not on disk. Screen contents are a memory buffer. Until you :w, cat will not see changes. Quitting with :q without :w leaves the file unchanged.
  • Scope: : only works from command mode. You cannot give :w while still in insert mode. Mandatory sequence: Esc: → command. The professor repeats escape-then-colon as gateway.
  • Assumption: line endings and page indicator. On empty file 0,0 and 1/1 are hints, not content lines. After writing, cursor position like 4,1 means fourth line, first column.
  • Scope: vi vs vim mapping. On modern systems both start vim improved; vim startup banner confirms. Core modes and :w/:q are identical.

Worked example — writing the buffer and quitting (four lines 35 characters and more)

Steps with a named file:

  1. While in insert mode, press Esc → command mode.
  2. Type : → cursor moves to bottom command line.
  3. Type w → write buffer to file named at startup. Message: practice New 4 lines, 35 characters (or similar) — reports lines and characters written. Cursor ends at 4,1 (fourth line, first column).
  4. Alternative without initial name:
  • Start with vim alone — no name.
  • Enter insert with a or i, type e.g., #include <stdio.h> (two lines, 19 characters).
  • Press Esc:w sample.c → writes to sample.c with message sample.c 2 lines, 19 characters and cursor at 2,0 or second line beginning.
  • File now exists; subsequent :w without name writes to sample.c.

Quitting variants:

  • :q — quit — succeeds only if no unsaved edits. If you edited and try :q, message No write since last change appears and it refuses.
  • :q! — quit without saving — ! is overriding option. It discards buffer changes and quits regardless. The professor types unsaved text then :q! and verifies with cat that changes are not on disk.
  • :wq — write and quit — writes buffer and quits to shell prompt. WQ means write and quit. Also :x is equivalent in many configurations (write if changed then quit).
  • After :wq shell prompt returns. Verify with cat sample.c or vim sample.c — latter shows color highlighting for .c files.

Sense-check: if cat sample.c after :wq does not show what you typed, you missed the Esc before : — the buffer never left memory.

Worked example — command mode cursor motion and editing

Once in command mode, alphabetic keys become motion and edit commands — they do not insert text. Classic vi navigation uses adjacent keys h, j, k, l:

  • h — left
  • l — right (lowercase L, not capital I — i is insert, clarified after a slip)
  • j — down
  • k — up

These four are adjacent on the keyboard, designed for touch typing. Demo: l moves right step by step, h left, j down, k up.

Other command-mode edits demonstrated:

  • x (lowercase) — delete single character at cursor. Repeated x deletes multiple chars. Example: delete STD from stdio.h by pressing x three times on that word.
  • w — move to beginning of next word. b — move to beginning of previous word. Word-wise motions for faster navigation.
  • ~ (tilde) — toggle case — changes lowercase to uppercase at cursor; pressing again toggles. Demo on i becoming I.
  • . (dot) — repeat last edit — redoes previous change.
  • J (capital) — join — joins next line onto current line, deleting the newline between them.

All execute in command mode without entering insert mode and without touching the command line at the bottom. The bottom command line is only for colon commands — it is literally the last line of the screen where : brings the prompt. Worksheet 4.7 asks to try each — x deletions, J joins, w/b word moves, ~ case toggles — and record what changed.

Speed note: these motions are why vi users never lift hands to a mouse. Large codebase edits — deleting a char here, joining a line, moving word by word — become rapid keyboard sequences; that rapid-fire hand movement is the hardcore programmer workflow the lecture links to staying on vi.

Pitfalls — mode and motion mistakes

  • Typing insert letters while in command mode. h will move left, not insert h. If letters do not appear, you are in command mode — press i.
  • Trying colon commands from insert mode. :w types as text. Must be Esc:.
  • Forgetting Esc before :q and losing work. Buffer without write plus :q is blocked; :q! discards. Remember buffer vs file separation.
  • Confusing l (lowercase L) with I or 1. Lecture slip corrected: l is right, i is insert. Adjacent cluster h j k l is the mnemonic.
  • Miscounting columns for i vs a. On a line ending at column 17, i inserts at 17, a at 18 — one column matters for mid-line typo fixes.
  • Expecting extension requirement. vi practice works with no extension; extension only adds highlighting convenience.

Q: Does vi require an extension like .c or .txt? A: No, extension is not mandatory. vi practice works without extension. But if you give .c, vim provides color highlighting for C syntax — keywords in different colors because it recognizes the language.

Q: What difference between i and a? What about capital A versus lowercase a? A: i inserts at the cursor position; a moves one column right then inserts — append after. o always opens a new line below regardless of position. Capital A versus lowercase a is a finer variant to explore in the worksheet, but the testable distinction is insert-at vs append-after; the one-column shift demonstrated (17 vs 18) is the exam point.

Q: How to know which mode I am in right now? A: Look at the bottom line. If it shows INSERT, you are in insert mode. If it shows filename with 5L, 41C and no INSERT, you are in command mode. If colon prompt : is at the very bottom, you are in command-line mode. The professor used sample.c 5L, 41C as the command-mode proof vs INSERT.

Exam note: Master the lineage ed line editor → vi visual interface → vim vi improved, and why vi persists for keyboard-only rapid editing. Know modes: command mode initial; i/a/o to insert; Esc to command; : to command-line. Know screen cues: tildes ~, 0,0, 1/1, New File, INSERT. Know i at cursor vs a one column ahead (append) vs o new line below. Know writing: :w to named file, :w <name> when started nameless, :wq write and quit, :q quit if no changes, :q! override discard, :x similar. Know motions in command mode: h left, j down, k up, l right, plus x delete char, w next word, b previous word, ~ toggle case, . repeat, J join. Remember buffer vs file and the mandatory Esc then : gateway. Worksheet 4.7 hands-on observations are examinable.

Recap and bridge: The VI editor completes the lecture arc from counting (wc) and classifying (file) through moving (mv), navigating (cd), comparing (cmp, comm, diff), and monitoring (top/ps) to actually changing files. Its modal design — command, insert, command-line — and pointer-based backends (arrays vs linked structures) explain why hardcore programmers remain on vi for speed where mice and graphical editors are absent.

Real-world and domain connection: vi/vim remains the default editor on servers, containers, and embedded systems accessed over SSH where graphical editors are unavailable. System administrators edit configs, developers patch code, and build engineers fix scripts — all with modal, mouse-free sequences that scale to large codebases. Knowing vi is a production gate skill: when nano is not installed and the network is SSH-only, vi is the only tool that can write the fix.

6.9.1 Starting vi and the Initial Screen

Trace — first start

  • vi practice → command mode screen: ~ rows, bottom line practice New File, cursor 0,0 page 1/1.
  • Type J Q C D P U → nothing inserts — proves command mode.
  • Press iINSERT appears, tildes disappear as you begin typing — now in insert.

6.9.2 Modes and How to Move Between Them

Takeaway: Mode identification is visual, not memory. Bottom line tells truth: INSERT = insert, 5L, 41C without INSERT = command, : at very bottom = command-line. Sequence iEsc:w/q is the gateway to persist or exit.

6.9.3 Inserting Text and the i versus a Distinction

Trace — column 17 vs 18

On a line ending at column 17: i keeps cursor at 17 and inserts there; Esc then a shows INSERT with cursor at 18 and appends after. Mid-line, o abandons the line and opens a fresh line below at column 0. That one-column difference is the test of whether you truly counted cursor columns.

6.9.4 Writing the Buffer to a File and Quitting

Trace — confirm with cat

After :w → buffer persists to file; cat practice shows what screen showed. After :wq → shell returns; cat sample.c confirms 2 lines, 19 characters written. After :q! with unsaved text → cat proves changes absent — discard worked. The lecture verifies each outcome with cat or re-opening with vim to see 5L, 41C and color.

6.9.5 Command Mode Cursor Motion and Editing

Trace — rapid fire without mouse

In command mode on a line containing #include <stdio.h>:

  • l l l moves three steps right over STD; x x x deletes STD<stdio.h> loses those chars.
  • w jumps to next word, b jumps back word.
  • On i, ~ toggles to I.
  • J on line 1 joins line 2 onto it, newline gone.
  • . repeats the last deletion.

Takeaway: Command-mode keys are verbs, not letters. h j k l move, x deletes, w/b jump words, ~ flips case, . repeats, J joins — all without leaving command mode or touching the bottom command line.

Exam Guidance Summary

This lecture is application-heavy and the professor flags exact question forms for each tool. Treat the list as a revision checklist and practice each command hands-on before the exam.

  • wc — counting: Know wc with no option (lines, words, bytes together) and isolated -l (lines), -w (words), -c (bytes). The demo totals 72 lines/users, 100 words, 4241 bytes for /etc/passwd are the reference numbers the examiner may reuse. The worksheet myfile.doc asks the same four counts. Remember wc -l /etc/passwd counts users because one user = one line; byte count equals character count for ASCII.
  • file — typing: Content, not extension, decides. Recognize ASCII text, C source, ASCII text, LSB shared object, dynamically linked, interpreter ... for GNU/Linux ..., and directory. A file named student.doc that contains ASCII will be ASCII text — that contrast tests whether you trust file over name.
  • mv — move and rename: mv zombie zoom renames one file; mv /OS/*.* /SP moves every file with an extension; mv /SP/*.c /OS filters by .c at the end. Remember mv moves — source disappears — unlike cp. Wildcard placement *.c at the end is the testable filter.
  • cd — navigation tricks: cd / = root, cd ~ = home of logged-in user, cd . = current (no move), cd .. = parent (write parent directory for full marks), cd ../.. or cd ../../ = grandparent. cd ./.. is still parent, not grandparent — expect a trick question on that exact string. Verify every move with pwd.
  • cmp — first mismatch only: cmp file1 file2 compares byte by byte and stops at the first difference, reporting differ: byte 189, line 5 style; identical files give no output (silence = same). It takes two operands only and later differences are not listed until the first is fixed. Developer use is current vs backup quick check.
  • comm — three columns: Requires sorted files; output is column 1 unique to file1, column 2 unique to file2, column 3 common. Suppress with -1, -2, -3 and combinations (-12 shows only common, -23 shows only unique to file1). Only two operands — third is rejected. An empty first column means nothing unique in file1. Read column-wise by TAB offset, not row-wise.
  • diff — edit script: Line-by-line script to make file1 identical to file2. Symbols a add, d delete, c change; numbers left = first file lines, right = second file lines. Know 2d1 (delete line 2 from first), 1a2 (add line 2 from second), 1,2d0 (delete 1–2 with 0 no counterpart), 3a2,3 (after line 3 add lines 2–3). Swapping operands inverts the script; body uses < for first file, > for second, --- for change. diff never edits — only suggests.
  • top and ps — process views: top is live, real-time, system-wide, showing total tasks, sleeping, CPU %, memory total/free/used and buffer/cache, plus rows for top itself per user and sshd. Quit with q. ps is a snapshot: plain ps shows current user only; ps aux shows all processes as a frozen dump. top real-time vs ps snapshot is the discriminator, and multiple top rows illustrate system-wide scope.
  • vi — editor: Lineage ed (line editor, one line at a time) → vi (visual interface, full screen) → vim (vi improved; vi and vim both start the improved engine). Backend concepts: two-dimensional array, linked list, doubly linked list, link matrix with BIOS/DOS character functions. Modes: command mode initial, i/a/o to insert, Esc back to command, : to command-line mode. Screen: tildes ~, 0,0 coordinates, 1/1 pages, New File, INSERT flag. Core i at cursor vs a one column ahead (append) vs o open new line below (mid-line still new line). Writing: :w to named file → 4 lines, 35 characters message, :w <name> when started nameless (sample.c 2 lines, 19 characters), :wq write and quit, :q quit only if no changes, :q! override discard, :x similar. Motion in command mode: h left, j down, k up, l right (adjacent keys), w next word, b previous word, x delete char, ~ toggle case, . repeat last edit, J join lines. Color highlighting for .c files. No extension required for filename. Worksheet 4.7 requires hands-on observation of each command — that practice is examinable.

Study advice: Treat repeated explanations as valuable — the professor explains comm columns three times with different phrasings and demonstrates diff with renamed Twinkle Twinkle / Little star because wording matters. Run each command yourself in any directory with two or three small files: try wc with and without options, file on different types, mv with *.* vs *.c, cd variants checked with pwd, cmp on identical vs edited copies, comm with and without -1/-2/-3 on sorted vs unsorted inputs, diff both operand orders, and vi creation of practice and sample.c to internalize mode switches and the mandatory Esc then : gateway.

Exam note: Command questions are recall plus interpretation — not just name, but what output looks like and what order or column means. Practice reading wc 72 100 4241, differ: byte 189, line 5, comm TAB lanes, diff 1,2d0 / 3a2,3, top header, and vi 5L, 41C as sentences before the exam so that parsing is automatic.

Key Industry Applications

  • Counting with wc -l: User audit via wc -l /etc/passwd or any data file; log triage wc -l /var/log/syslog; record validation wc -l data.csv before load; build gate ls | wc -l to confirm file counts. wc -c checks file size before commit or transfer. Counting underpins grep | wc, who | wc pipelines used in monitoring scripts.
  • Triaging with file: Server triage of unknown binaries vs text vs source before viewing, compiling, or executing — essential where extensions are stripped or unreliable. Build verification that an artifact is LSB shared object, dynamically linked for the correct architecture before deploy; submission check that an assignment is C source, ASCII text before gcc; directory detection to decide between cat and cd/ls.
  • mv for deploy-time reorganization: Moving .c sources between src and SP/OS build directories, archiving mv *.log archive/, renaming binaries mv a.out service, atomic config updates mv new.conf app.conf within a filesystem. Remembering that source disappears avoids data loss; bulk patterns *.* and *.c at the end are production file-set selectors.
  • cmp and diff for change validation: cmp as fast developer gate verifying that a deployed binary matches the built artifact, that a restored config is byte-identical to the known-good backup, or that a copy succeeded — silence means go, byte 189, line 5 means investigate. diff for detailed code review between versions, patch creation, and drift reconciliation — it produces the exact adds/deletes/ changes needed to make a current file match a template, which are then applied manually via vi or patch.
  • comm for set reconciliation: Finding commonality between two sorted lists — e.g., reconciling user lists from two systems, comparing two sorted datasets, or auditing directory snapshots comm file.info1 file.info2 (today vs backup). Column suppression extracts actionable sets: comm -12 intersection, comm -23 only-in-first for removal, comm -13 only-in-second for provisioning.
  • top and ps aux for production monitoring: Watching top for runaway CPU consumers, memory pressure, and buffer/cache health; confirming daemons like sshd, nginx are alive; understanding process ownership across users on shared hosts. ps aux as the scriptable snapshot — ps aux | grep for checks, ps aux | wc -l for counts, cron jobs that snapshot and alert. The lecture's three-to-five top rows demo is the minimal illustration of multi-tenant hosting.
  • vi/vim as the ubiquitous server editor: The fastest keyboard-only editor for programmers and administrators editing files over SSH where graphical editors are unavailable. Its modal design eliminates mouse dependence for insert, delete, word navigation, case toggle, line joining, and repetitive edits. When containers or minimal installs lack nano, vi is the guaranteed editor that can write the fix — mastery of modes, Esc then : gateway, and buffer vs file write is a baseline operations skill.

Domain thread: From wc counting records to file classifying, mv relocating, cd navigating, cmp/comm/diff comparing, top/ps monitoring, and vi editing, the lecture builds a complete loop for systems programming on Linux: measure, identify, organize, navigate, compare, observe, and change — all from the command line without a graphical interface.

SP Lecture 6 notes · Linux Commands and the VI Editor

Systems Programming· postgraduate· 2026-08-20

Sections Breakdown

1The wc Command — Counting Lines, Words and Bytes

wc counts lines, words and bytes; plain wc prints all three, -l/-w/-c isolate; demo on /etc/passwd shows 72 lines/users, 100 words, 4241 bytes.

2The file Command — Identifying What Kind of File You Have

file probes content not name; reports ASCII text, C source, LSB shared object dynamically linked, or directory.

3The mv Command — Move and Rename

mv renames (mv zombie zoom) or moves groups (mv /OS/*.* /SP and mv /SP/*.c /OS); source disappears, unlike cp.

4Navigating with cd — Root, Home, Current and Parent

cd symbols: / root, ~ home, . current (no move), .. parent, ../.. grandparent; cd ./.. still parent; verify with pwd.

5cmp — Byte-by-Byte Comparison That Stops at the First Difference

cmp compares two files byte by byte, stops at first mismatch reporting byte 189 line 5, silence means identical; two operands only.

6comm — Three Columns for Two Sorted Files

comm on two sorted files shows column1 unique file1, column2 unique file2, column3 common; -1 -2 -3 suppress columns; third file rejected.

7diff — Line-by-Line Difference and the Editing Script

diff outputs edit script to make file1 identical to file2: a add, d delete, c change; formats 1a2, 2d1, 1,2d0, 3a2,3; swapping inverts; < first file > second.

8top and ps — Viewing Processes in Real Time

top is live system-wide interactive view (tasks, sleeping, CPU%, memory, sshd, q to quit); ps is snapshot, ps aux all processes.

9The VI Editor — From Line Editing to Full-Screen Visual Editing

vi lineage ed -> vi visual -> vim improved; modes command/insert/command-line; i at cursor a append+1 o new line; writes :w :wq :q :q! ; motions h j k l x w b ~ . J.

10Exam Guidance Summary

Consolidated exam checklist for all commands: wc, file, mv, cd, cmp, comm, diff, top/ps, vi with exact question forms and tricky variants.

11Key Industry Applications

Production uses: wc -l audits, file triage, mv atomic deploys, cmp/diff verification, comm set reconciliation, top/ps monitoring, vi over SSH.

Postgraduate students in Systems Programming

Exam Revision Notes

Below is the distilled, exam-ready core. Every entry comes from the full explanation above. Use this section for rapid review; return to the main notes when a point needs more context.

The wc Command — Counting Lines, Words and Bytes

Must-know: wc prints lines words bytes together; -l lines, -w words, -c bytes; lines count users in /etc/passwd

⚠️ Top pitfall: Confusing bytes with characters and words with lines; word count in /etc/passwd is low because colons are not whitespace

Self-check: What does wc -l /etc/passwd return and what does it mean?

Connects to: 6.8

The file Command — Identifying What Kind of File You Have

Must-know: file <pathname> inspects content; recognize ASCII text, C source, LSB shared object dynamically linked, directory

⚠️ Top pitfall: Trusting extension over file output; cat on a binary after file says shared object

Self-check: What does file student.doc report when content is plain ASCII and why?

Connects to: 6.3, 6.9

The mv Command — Move and Rename

Must-know: mv moves not copies; patterns zombie->zoom, *.* bulk move, *.c filtered move at end selects

⚠️ Top pitfall: Using mv when cp was intended; placing *.* instead of *.c and overwriting without -i

Self-check: How to move only .c files from /SP back to /OS and why verify with ls?

Connects to: 6.2, 6.4

Navigating with cd — Root, Home, Current and Parent

Must-know: cd / root, cd ~ home, cd . current, cd .. parent (write parent directory), cd ../.. grandparent; cd ./.. is parent not grandparent

⚠️ Top pitfall: Confusing / with ~ or ./.. with grandparent; writing previous instead of parent directory loses marks

Self-check: What does cd ./.. do versus cd ../.. and how does pwd prove it?

Connects to: 6.3, 6.5

cmp — Byte-by-Byte Comparison That Stops at the First Difference

Must-know: cmp file1 file2 stops at first mismatch with byte and line; identical gives no output; two operands only

⚠️ Top pitfall: Expecting full diff; misreading silence as failure; confusing byte number with line number

Self-check: Why does a second later change not appear after cmp reports byte 189 line 5?

Connects to: 6.6, 6.7

comm — Three Columns for Two Sorted Files

Must-know: comm requires sorted files, three columns uniques and common, suppress with -1/-2/-3, only two files; empty first column means nothing unique

⚠️ Top pitfall: Reading row-wise not column-wise; unsorted input; supplying three files

Self-check: What does comm -12 num1.txt num2.txt output and why?

Connects to: 6.5, 6.7

diff — Line-by-Line Difference and the Editing Script

Must-know: diff a/d/c with left numbers first file right numbers second; 1a2 add line2, 2d1 delete line2, 1,2d0 delete 1-2 with 0, 3a2,3 add 2-3; swapping inverts; does not edit

⚠️ Top pitfall: Guessing 1a0 instead of 1a2; reading < > backwards; thinking diff edits automatically

Self-check: Interpret 3a2,3 with body > 4 > 5 for num1 1 2 3 vs num2 3 4 5

Connects to: 6.5, 6.6

top and ps — Viewing Processes in Real Time

Must-know: top live real-time with q quit vs ps snapshot; ps aux all processes; header tasks sleeping CPU memory buffer cache

⚠️ Top pitfall: Forgetting q to exit top; thinking ps alone shows all processes

Self-check: Why do three top rows appear when three users run top?

Connects to: 6.1, 6.9

The VI Editor — From Line Editing to Full-Screen Visual Editing

Must-know: vi modes and gates: command initial, i/a/o to insert, Esc to command, : to command-line; i at vs a after vs o new line; writes :w :wq :q :q! and motions h j k l

⚠️ Top pitfall: Typing colon commands in insert mode; forgetting buffer vs file; mixing l with I

Self-check: How to tell insert vs command mode from bottom line and what does :q! do?

Connects to: 6.2, 6.7

Exam Guidance Summary

Must-know: All command patterns, outputs, and trick variants listed in exam checklist

⚠️ Top pitfall: Not practicing hands-on; missing that unsorted comm or operand order in diff inverts answer

Self-check: List the four cd symbols and their correct full-term answers for marks

Connects to: 6.1, 6.4, 6.6, 6.7

Key Industry Applications

Must-know: Each command's production role in pipelines and server operations

⚠️ Top pitfall: Treating lecture commands as toy only; not linking cmp silence or comm columns to automation gates

Self-check: Which command pipeline validates that a deployed artifact matches the build?

Connects to: 6.5, 6.6, 6.8

Was this lecture useful?

Loading comments…
🤖

BitsNotes AI Assistant

Subject Notes Assistant

Configure AI Chat

Choose how to access the chatbot
Have your own API key?

Switch to "Bring Your Own Key" tab above for unlimited access with any OpenAI-compatible provider.

🔑 Enter API key above to fetch live models from provider, or enter model name manually.
OpenAI-Compatible API Support

Choose any provider preset (Gemini, DeepSeek, Kimi, GLM, MiniMax, Qwen, OpenAI, Groq, Ollama, etc.) or enter a custom endpoint URL.

Security & Privacy First

Your API key is sent directly from your browser to your specified provider. BitsNotes servers never store or see your key.