Linux Commands and the VI Editor
# 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;-lcounts newline characters - word = maximal sequence of non-whitespace characters bounded by whitespace;
-wcounts those tokens - byte = single 8-bit unit;
-ccounts bytes
Syntax:
wc [ -l | -w | -c ] [ file ... ]
wc filewith no option printslines words bytes filenamein that order.wc -l fileprints lines only.wc -w fileprints words only.wc -c fileprints bytes only.- With multiple files, wc also prints a
totalline. With no filename and data piped in, it reads standard input. Options-l,-w,-ccan be combined aswc -lwbut 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/passwd→72 100 4241 /etc/passwd- 72 lines
- 100 words (whitespace-separated tokens; note
/etc/passwduses colons, so many lines are one word) - 4241 bytes
Isolated counts:
wc -l /etc/passwd→72— answer to "how many users?" = 72. This includes the student account,root, and temporary users added earlier withadduser.wc -w /etc/passwd→100wc -c /etc/passwd→4241
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.doc — wc 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 -lcounts 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/passwdcolon is not whitespace, sowc -wunderreports human-expected fields. For colon fields usecut -d:orawk -F:. - Bytes vs characters.
-creports bytes. With ASCII, bytes = characters. With UTF-8 containing multi-byte characters, usewc -mfor characters. The lecture uses ASCII, so 4241 bytes equals characters. - Binary files.
wcwill count bytes on a binary, but lines and words are meaningless. Usewc -conly for binaries. - Empty or missing files.
wcon empty prints0 0 0. No file or permission denied is an error, not zero.
Pitfalls — what trips beginners
- Mixing up
-cand-m. Remember:-cis bytes,-mis characters. In the exam write "bytes (equals characters for ASCII)". - Forgetting that no option prints all three. Students run
wc -land 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, notwc -w.
Q: Where do we get user information in a Linux system — what file holds user ID and group ID? A: In
/etc/passwdinside the/etcfolder. 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 iswc -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/passwdwith one user per line, report lines, words, bytes separately and together. - Step 1 — combined:
wc /etc/passwd→72 100 4241 /etc/passwd— printslines words bytes filename. - Step 2 — lines only:
wc -l /etc/passwd→72— 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/passwd→100— shows colon-joined records count as few words. - Step 4 — bytes only:
wc -c /etc/passwd→4241— 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
.doccontaining only ASCII will be reported asASCII text, and a file namedF1with no extension but containing a compiled binary will be reported asLSB shared object. - The description often carries detail after the base type:
C source, ASCII textmeans 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.txt→output.txt: ASCII text— generic text output, same base type.file fork1.c→fork1.c: C source, ASCII text— text but with C markers (#include,;, braces) recognized as C source.file student.doc→student.doc: ASCII text— despite the.docname the content in this example is plain ASCII text. The name did not decide; the content did.file F1→F1: 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 youcator 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
emptyorASCII textwithout language tag because there is not enough pattern to classify. - Assumption: magic database is present.
filerelies 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 textversusUTF-8 Unicode textorC sourcedistinction is heuristic. Verification withcator a compiler still matters for critical steps. - Directories vs regular files:
fileon 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.docbeingASCII textsurprises students who expect Word format. Remember: on Linux, extension is convention only;filereads bytes. - Cat on a binary. Running
cat F1afterfile F1reports shared object will dump binary garbage to the terminal. IffilesaysLSB shared object, do notcatit. - Forgetting that directories are a type. Beginners run
file mydirand expect text. The correct reading isdirectory— handle withls/cd, notcat. - 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:
file /etc/passwd→ASCII text— system text database.file output.txt→ASCII text— user text file, same family.file F1→LSB shared object, dynamically linked, interpreter ... , for GNU/Linux ...— binary, not text, needs execution not viewing.file fork1.c→C source, ASCII text— text with C syntax tag, candidate forgcc.file mydir→directory— container type.file student.doc→ASCII 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— filezombiebecomeszoomin the same directory. Verify withls. Same form renames a directory. - Move a group into a directory:
mv /OS/*.* /SP— every file in/OSwhose name contains a dot with an extension (*.*= any name, dot, any extension) is moved into/SP. Afterwardls /OSshows them gone;ls /SPshows them present. - Filtered move:
mv /SP/*.c /OS— only C sources are moved back —fork1.c,fork2.c,fork3.c,zombie.cetc. The pattern*.cis placed at the end to filter by extension.*.*would move everything with a dot;*.cnarrows 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.
- Bulk move with extension filter:
mv /OS/*.* /SP
- Shell expands
/OS/*.*to every pathname in/OScontaining a dot. mvmoves each into/SP.- Check:
ls /SPnow lists the moved files;ls /OSshows those names gone. The move is literal — sources vanished from/OS.
- Rename:
mv zombie zoom
- Single source to new name in same directory.
- Check:
lsshowszombiedisappeared,zoomappeared with same content. The inode is the same file under a new name.
- Return filtered:
mv /SP/*.c /OS
- Shell expands
/SP/*.ctofork1.c,fork2.c,fork3.c,zombie.cetc. in/SP. mvmoves only those.cfiles back to/OS.- Check:
ls /OSregains the C sources;ls /SPretains only non-.cfiles (if any). Placing*.cat 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
mvis fast pointer update. Across filesystems or devices it must copy then delete, so time and space depend on size. - Assumption: wildcard expansion by shell.
mvnever sees*; the shell expands it first. An empty expansion (no match) behavior depends on shell settings — with defaultnullgloboff, 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
mvwhen you meantcp. The source disappears. If safety is needed, copy first or usecpthen verify before removing. - Writing
mv /OS/*.* /SPasmv /OS/* /SPormv *.*incorrectly.*.*means name dot extension; plain*includes extensionless files likezombie. Choose the pattern that matches the intended set. - Placing wildcard wrong for
.cfiles.mv /SP/*.* /OSwould move everything with a dot, not only C sources. The correct filter ismv /SP/*.c /OSwith*.cat the end. - Overwriting without warning. If a file with the same name exists at destination, default
mvoverwrites. Usemv -ifor 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 /OSshowsfork1.c fork2.c fork3.c zombieand other dotted files. - After
mv /OS/*.* /SP:ls /SPlists the moved files;ls /OSshows none of those dotted names remain — some extensionless name may remain if it lacked a dot. - After
mv zombie zoom:lsshowszoomnotzombie— same file, new label. - After
mv /SP/*.c /OS:ls /SPno longer shows*.cfiles;ls /OSregainsfork1.c fork2.c fork3.cand similar.cfiles, verified by the professor withlson both directories. The filter succeeded because*.cat 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.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
difforcommwhich 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.txtcreates an identical copy.
Step sequence from the live demo:
cmp results.txt results1.txt→ no output → files are identical. Silence is success. The professor emphasizes: no message means sameness, not error.
- Edit
results.txt— change a single character, for example replace a9with3on line 5 using the editor, save.
cmp results.txt results1.txt→results.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.
- Make a second change farther down, e.g., change another word to
execute. Runcmpagain → stillresults.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 (
\nvs\r\n), trailing spaces, or invisible characters count as bytes and will trigger a mismatch. - Scope: two operands only.
cmpis notcommordiffwith 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
commordiff. - 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
cmpto list all changes likediff. It does not — it stops at the first. If you need all differences, usediffor 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 5gives both; byte is absolute from start, line is line count. They are not the same unit. - Running
cmpon unsorted vs sorted expectation. Sorting is irrelevant tocmp— it compares raw bytes. Sorting matters forcomm, not here. - Trying three files.
cmp a b cis an error. Usecommordiffworkflows 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.txtcopied toresults1.txt→ identical pair.cmpsilently succeeds. - First edit — single byte change on line 5:
cmp results.txt results1.txt→differ: byte 189, line 5— first mismatch located. - Second edit — additional change later in file:
cmpstill reportsdiffer: byte 189, line 5— provescmpnever scans beyond the first difference until that difference is fixed. Only after reconciling byte 189 would a rerun expose the laterexecutechange.
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:
-1suppresses column 1 (unique to file1 disappears).-2suppresses column 2.-3suppresses column 3 (common disappears, leaving only differences).- Combinations:
-12shows only common lines;-13shows only unique to file2;-23shows only unique to file1;-123would 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.txtprints:- Column 1:
12— unique to first - Column 2:
67— unique to second - Column 3:
345— 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 2and6 7without common — difference view.
D. Only two operands:
cp num1.txt num3.txtthencomm num1.txt num2.txt num3.txt→ error: only two arguments permitted. The professor intentionally tries three files to provecommcan 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 -nfirst; for text usesort. 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
touchthencat >versus both viacatcan mislead expectations:touchcreates 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.
-1does not delete data; it hides column 1 from view. Pipingcomm -12extracts 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 linevssecond.txt=First line+Second line→ column 1 empty, column 2Second line, column 3First line. - Supplying three files.
commaccepts only two operands — third is rejected. To compare three sets, run pairwisecommor combine with other tools. - Forgetting sorted prerequisite. Running
common unsorted lists and wondering why columns interleave is the top failure; sort first. - Mixing up
-12vs-23meaning.-12shows only common (suppress 1 and 2),-23shows 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.txtyields (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:
ais add — a line from the second file must be added to the first.dis delete — a line from the first file must be deleted.cis 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;0indicates 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< oldthen---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:
1a2followed 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:
2d1followed 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.txt→Twinkle Twinklesecond.txt→Twinkle TwinkleplusLittle staron second line.
diff first.txt second.txt→1a2with body> Little star— addLittle starfrom second file after line 1 of first file.diff second.txt first.txt→2d1with 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, with0indicating 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.
diffcompares whole lines including newline. A trailing newline difference makes otherwise identical last lines differ. - Scope: script not edit.
diffnever modifies files. You must apply adds/deletes/changes manually, for example with the VI editor, or viapatch. - Scope: default output is normal diff. The lecture uses normal format (
n a mwith</>). Other formats (-uunified,-ccontext) exist but the exam targets normala/d/cwith< > ---. - Assumption: left is source, right is target.
diff A Bplans to change A to match B. Remember direction when interpreting1a2vs2d1.
Pitfalls — what trips beginners
- Guessing
1a0instead of1a2.0appears only with delete-to-zero (1,2d0), not as add source. Add source is actual line number in second file —2or2,3. - Forgetting operand order inversion.
diff A Banddiff B Agive inverse scripts. Swapping operands flipsatod. If question asks "make fileA identical to fileB," start with fileA first. - Reading
<vs>backwards.<is first file,>is second.< Second lineunder2d1means delete that line from first. - Thinking
diffedits automatically. A student asked this directly — answer: never. It only suggests edits; you must edit. - Mixing
commcolumns withdiffhunks.commsuppresses columns with-1etc.;diffhunks 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.txtwheresecond.txtis two lines,first.txtone line → guess2d1with< Second line— correct. It says delete line 2 from longer first operand. - Reverse:
diff first.txt second.txt→ many guessed1a0— corrected to1a2with> Second line— add line 2 from second file after line 1. The correction teaches that the number afterais 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 — wantnum1→num2- 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,5 — num2. 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
topeach appear as a separate row owned by different users includingrootand student accounts.sshdalso 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
psalone lists processes for the current user.ps aux— options often written asps auxor verballyPSAUX— lists all processes of the system, similar coverage totopbut 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 runsps auxto 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:
- One student runs
top→ process table shows that user'stopplussshdand system tasks. - Two more students type
topon other terminals →toplist now shows threetoprows, each owned by a different user account. The increment proves system-wide scope. - 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.
- Press
qintop→ live view exits, returns to shell prompt. - Immediately run
ps aux→ static list shows the samesshdand user processes, but thetoprows from students who quit are gone. The names overlap withtop'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:
topis system-wide by default. Some configurations filter to user, but default and the lecture's demo are system-wide. - Assumption:
pswithoutauxis user-limited. Beginners who runpsand see few rows think few processes exist; addauxfor the full system picture. - Scope: interactive vs scriptable.
topis for interactive monitoring (needsqto exit);ps auxis for scripts that need a static dump piped togreporwc. - 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.topfills the terminal and seems stuck; the fix is simplyq, not Ctrl+C. Students who force-close lose the header reading. - Mixing
psvsps aux. Runningpsand concluding "no sshd is running" is wrong —sshdappears withps auxbut not plainpsunless it is your process. - Thinking
toprows per user mean multiple daemons. Threetoprows are three invocations of thetopprogram 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
topjitter every refresh; do not report them as constants. For a stable number for a report, use aps auxsnapshot 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:
toprefreshes: CPU % jitters, tasks count ticks, three to fivetoprows appear as three to five users invoke it.ps auxprints: same process names (topat that instant,sshd, shells) but one view only. Onlytopupdates live as users start and stoptop.
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. vi — visual interface — opens the wall to a full-screen canvas where you see the whole file and move freely. vim — vi 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 with5L, 41Cstyle (lines, characters) and noINSERT. - Insert mode — where typed characters actually enter the buffer and appear on screen. Entered by pressing
ioraoro. Screen indicatesINSERTwhen 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 likew,w <filename>,q,q!,wq,x.
Movement between modes:
- Start
vi practice→ command mode. - Press
ioraoro→ insert mode (screen showsINSERT). - Press
Esc→ back to command mode. - From command mode press
:→ command-line mode (cursor goes to bottom line prompt). - After executing (
w,q, etc.) or pressingEsc→ 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 practiceorvim practice— with filename you intend to create.- Also
vimalone 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 Fileif it does not exist. - Bottom right shows cursor coordinates and page. At empty start it shows
0,0meaning first column, first row, page1/1. As you move, page numbers like1/1and column numbers update. - If you try arrow keys or type letters like
J,Q,C,D,P,Uat this stage, nothing inserts.Pwould be paste,Uundo — but without text they do nothing. Typingh,j,k,lalso 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:
i— insert at cursor position. Cursor stays where it was; next typed character appears at that cursor cell, pushing existing text right.a— append — moves cursor one column to the right first, then inserts. You append after the cursor rather than at it.o— open a new line. Regardless of where you are mid-line,ocreates 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→ showsINSERTwith cursor still at 17; typing inserts exactly there. - Press
Esc→ command mode → pressa→ showsINSERTbut 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,catwill not see changes. Quitting with:qwithout:wleaves the file unchanged. - Scope:
:only works from command mode. You cannot give:wwhile 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,0and1/1are hints, not content lines. After writing, cursor position like4,1means fourth line, first column. - Scope:
vivsvimmapping. On modern systems both startvimimproved;vimstartup banner confirms. Core modes and:w/:qare identical.
Worked example — writing the buffer and quitting (four lines 35 characters and more)
Steps with a named file:
- While in insert mode, press
Esc→ command mode. - Type
:→ cursor moves to bottom command line. - 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 at4,1(fourth line, first column). - Alternative without initial name:
- Start with
vimalone — no name. - Enter insert with
aori, type e.g.,#include <stdio.h>(two lines, 19 characters). - Press
Esc→:→w sample.c→ writes tosample.cwith messagesample.c 2 lines, 19 charactersand cursor at2,0or second line beginning. - File now exists; subsequent
:wwithout name writes tosample.c.
Quitting variants:
:q— quit — succeeds only if no unsaved edits. If you edited and try:q, messageNo write since last changeappears 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 withcatthat changes are not on disk.:wq— write and quit — writes buffer and quits to shell prompt.WQmeans write and quit. Also:xis equivalent in many configurations (write if changed then quit).- After
:wqshell prompt returns. Verify withcat sample.corvim sample.c— latter shows color highlighting for.cfiles.
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— leftl— right (lowercase L, not capital I —iis insert, clarified after a slip)j— downk— 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. Repeatedxdeletes multiple chars. Example: deleteSTDfromstdio.hby pressingxthree 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 onibecomingI..(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.
hwill move left, not inserth. If letters do not appear, you are in command mode — pressi. - Trying colon commands from insert mode.
:wtypes as text. Must beEsc→:. - Forgetting
Escbefore:qand losing work. Buffer without write plus:qis blocked;:q!discards. Remember buffer vs file separation. - Confusing
l(lowercase L) withIor1. Lecture slip corrected:lis right,iis insert. Adjacent clusterh j k lis the mnemonic. - Miscounting columns for
ivsa. On a line ending at column 17,iinserts at 17,aat 18 — one column matters for mid-line typo fixes. - Expecting extension requirement.
vi practiceworks 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 linepractice New File, cursor0,0page1/1.- Type
J Q C D P U→ nothing inserts — proves command mode. - Press
i→INSERTappears, 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 i → Esc → : → 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>:
lllmoves three steps right overSTD;xxxdeletesSTD→<stdio.h>loses those chars.wjumps to next word,bjumps back word.- On
i,~toggles toI. Jon 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: Knowwcwith no option (lines, words, bytes together) and isolated-l(lines),-w(words),-c(bytes). The demo totals72lines/users,100words,4241bytes for/etc/passwdare the reference numbers the examiner may reuse. The worksheetmyfile.docasks the same four counts. Rememberwc -l /etc/passwdcounts users because one user = one line; byte count equals character count for ASCII.file— typing: Content, not extension, decides. RecognizeASCII text,C source, ASCII text,LSB shared object, dynamically linked, interpreter ... for GNU/Linux ..., anddirectory. A file namedstudent.docthat contains ASCII will beASCII text— that contrast tests whether you trustfileover name.mv— move and rename:mv zombie zoomrenames one file;mv /OS/*.* /SPmoves every file with an extension;mv /SP/*.c /OSfilters by.cat the end. Remembermvmoves — source disappears — unlikecp. Wildcard placement*.cat 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 ../..orcd ../../= grandparent.cd ./..is still parent, not grandparent — expect a trick question on that exact string. Verify every move withpwd.cmp— first mismatch only:cmp file1 file2compares byte by byte and stops at the first difference, reportingdiffer: byte 189, line 5style; 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,-3and combinations (-12shows only common,-23shows 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. Symbolsaadd,ddelete,cchange; numbers left = first file lines, right = second file lines. Know2d1(delete line 2 from first),1a2(add line 2 from second),1,2d0(delete 1–2 with0no counterpart),3a2,3(after line 3 add lines 2–3). Swapping operands inverts the script; body uses<for first file,>for second,---for change.diffnever edits — only suggests.topandps— process views:topis live, real-time, system-wide, showing total tasks, sleeping, CPU %, memory total/free/used and buffer/cache, plus rows fortopitself per user andsshd. Quit withq.psis a snapshot: plainpsshows current user only;ps auxshows all processes as a frozen dump.topreal-time vspssnapshot is the discriminator, and multipletoprows illustrate system-wide scope.vi— editor: Lineageed(line editor, one line at a time) →vi(visual interface, full screen) →vim(vi improved;viandvimboth 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/oto insert,Escback to command,:to command-line mode. Screen: tildes~,0,0coordinates,1/1pages,New File,INSERTflag. Coreiat cursor vsaone column ahead (append) vsoopen new line below (mid-line still new line). Writing::wto named file →4 lines, 35 charactersmessage,:w <name>when started nameless (sample.c 2 lines, 19 characters),:wqwrite and quit,:qquit only if no changes,:q!override discard,:xsimilar. Motion in command mode:hleft,jdown,kup,lright (adjacent keys),wnext word,bprevious word,xdelete char,~toggle case,.repeat last edit,Jjoin lines. Color highlighting for.cfiles. 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 viawc -l /etc/passwdor any data file; log triagewc -l /var/log/syslog; record validationwc -l data.csvbefore load; build gatels | wc -lto confirm file counts.wc -cchecks file size before commit or transfer. Counting underpinsgrep | wc,who | wcpipelines 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 isLSB shared object, dynamically linkedfor the correct architecture before deploy; submission check that an assignment isC source, ASCII textbeforegcc; directory detection to decide betweencatandcd/ls.
mvfor deploy-time reorganization: Moving.csources betweensrcandSP/OSbuild directories, archivingmv *.log archive/, renaming binariesmv a.out service, atomic config updatesmv new.conf app.confwithin a filesystem. Remembering that source disappears avoids data loss; bulk patterns*.*and*.cat the end are production file-set selectors.
cmpanddifffor change validation:cmpas 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 5means investigate.difffor 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 viaviorpatch.
commfor set reconciliation: Finding commonality between two sorted lists — e.g., reconciling user lists from two systems, comparing two sorted datasets, or auditing directory snapshotscomm file.info1 file.info2(today vs backup). Column suppression extracts actionable sets:comm -12intersection,comm -23only-in-first for removal,comm -13only-in-second for provisioning.
topandps auxfor production monitoring: Watchingtopfor runaway CPU consumers, memory pressure, and buffer/cache health; confirming daemons likesshd,nginxare alive; understanding process ownership across users on shared hosts.ps auxas the scriptable snapshot —ps aux | grepfor checks,ps aux | wc -lfor counts, cron jobs that snapshot and alert. The lecture's three-to-fivetoprows demo is the minimal illustration of multi-tenant hosting.
vi/vimas 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 lacknano,viis the guaranteed editor that can write the fix — mastery of modes,Escthen: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
Sections Breakdown
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.
file probes content not name; reports ASCII text, C source, LSB shared object dynamically linked, or directory.
mv renames (mv zombie zoom) or moves groups (mv /OS/*.* /SP and mv /SP/*.c /OS); source disappears, unlike cp.
cd symbols: / root, ~ home, . current (no move), .. parent, ../.. grandparent; cd ./.. still parent; verify with pwd.
cmp compares two files byte by byte, stops at first mismatch reporting byte 189 line 5, silence means identical; two operands only.
comm on two sorted files shows column1 unique file1, column2 unique file2, column3 common; -1 -2 -3 suppress columns; third file rejected.
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.
top is live system-wide interactive view (tasks, sleeping, CPU%, memory, sshd, q to quit); ps is snapshot, ps aux all processes.
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.
Consolidated exam checklist for all commands: wc, file, mv, cd, cmp, comm, diff, top/ps, vi with exact question forms and tricky variants.
Production uses: wc -l audits, file triage, mv atomic deploys, cmp/diff verification, comm set reconciliation, top/ps monitoring, vi over SSH.
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?
BitsNotes AI Assistant
Subject Notes AssistantConfigure AI Chat
Choose how to access the chatbotSigned in as
Powered by BitsNotes — 20 messages per day. No API key needed. Want unlimited access? Use "Bring Your Own Key" mode.
Sign in to use AI Chat
Get 20 free AI messages per day to ask questions about your lecture notes. Sign in with Google or GitHub — it takes 5 seconds.
Sign In to BitsNotesSwitch to "Bring Your Own Key" tab above for unlimited access with any OpenAI-compatible provider.