Skip to main content
Systems Programming

Linux Commands and File System Navigation

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

4.1 Inter-User Communication — write and wall

4.1.1 write — Two-Way Channel to a Single User

Hook: Imagine you and a classmate are logged into the same Linux server in two different labs — no phone, no chat app — yet you can still open a private, live text channel directly inside the terminal. How?

Intuition and analogy: Think of write like passing a paper note through a single desk slot. Only one recipient's desk has that slot, and once you open it, paper flows both ways until one of you closes the slot. The analogy maps cleanly: the username is the desk label, your keystrokes are the paper, and Ctrl + D is closing the slot. Where the analogy breaks: unlike paper notes, write is live and interleaves with whatever the other user is doing — it can interrupt their screen, so you must coordinate turns with conventions like (o) for over and (oo) for over-and-out.

Formalize — what write is and how it works:

  • Definition: write is a standard UNIX command that opens a two-way communication channel between two users who are currently logged in on the same system. It copies lines typed on one user's terminal to the other user's terminal and vice versa.
  • Syntax: write username [ttyname]
  • username — the login name of the target user as shown by who. This is required. Example: write nico or write ubuntu.
  • ttyname — optional terminal line (e.g., tty2, pts/0) shown in the second column of who. You need it only when the same user is logged in on multiple terminals and you want to pick one.
  • After you press Enter, the target sees Message from you on ttyX ... and you see Message from username .... Now anything you type goes to their screen, anything they type comes to yours.
  • Session lifecycle:
  1. Initiator types write mary and presses Enter.
  2. Both sides type freely. Each line appears on the other side after Enter.
  3. Either side presses Ctrl + D — the end-of-file character — which signals no more input. This returns that user to the shell prompt (\$). The other side sees EOF and then also presses Ctrl + D or DELETE to exit. DELETE/Ctrl-C can also interrupt, but Ctrl + D is the clean convention taught here.
  • Permissions: The target's terminal must allow messages. mesg n blocks writes; mesg y allows them. When blocked, write reports permission denied or user has messages disabled.

Worked example — opening and closing a write session:

Setup: Two users, you (ttyA) and mary (tty7), both logged in as shown by who.

Steps on your terminal:

\$ who
mary  tty7  Sep 25 19:03
you   ttyA  Sep 25 23:01
\$ write mary
did you forget lunch? (o)

What Mary sees:

Message from you on ttyA at 23:02 ...
did you forget lunch? (o)

Mary replies on her terminal (she already typed write you to answer):

ten minutes (o)

What you see:

ten minutes (o)
ok (oo)

Closing: You press Ctrl + D → you see \$ prompt and EOF on her side. She presses Ctrl + D → both back at \$.

Sense-check: After Ctrl + D, pwd and who work normally — you are back in the shell, not inside a subshell. If you forget (o) convention, lines still interleave but become unreadable, so discipline matters.

Scope and assumptions — when write applies:

  • Assumption: Both users are logged into the same host and reachable via the same file system namespace. write does not cross machines or networks by itself; for that you need mail, ssh, or network chat.
  • Scope: Works for plain text only, no file transfer, no history. The channel is ephemeral — nothing is saved unless you redirect.
  • Breaks when: Target is not logged in (write: user not logged in), target has mesg n, or the system is single-user. Also, graphical desktop notifications may hide terminal messages.

Visual intuition: Picture two vertical terminal windows side by side, each with a prompt at the bottom. A horizontal arrow labeled write mary opens a pipe between them. Keystrokes flow as thin lines across the pipe; Ctrl + D is a valve that closes the pipe and the arrow disappears. The x-axis is time (before → during → after channel), the y-axis is who is typing. Landmarks: the Message from... banner at channel start, the (o) turn markers mid-stream, and the EOF/\$ at channel close. Takeaway: the channel is temporary and symmetric.

Pitfalls:

  • Confusing write with wall or mail: write is one user, wall is all users, mail is asynchronous inbox. Picking wall for a private note broadcasts to everyone — noisy and impolite on a shared server.
  • Forgetting to handle tty when user appears twice in who: If mary appears on tty7 and tty8, write mary may pick the wrong one or fail with mary is logged in more than once; use tty. Always check who's second column first.
  • Not signaling turns: Without (o)/(oo), both sides type at once and output garbles. The protocol is social, not enforced by the command.
  • Thinking Ctrl + C is the clean exit: Ctrl + C kills the process but Ctrl + D (EOF) is the documented clean end that the receiver sees as EOF. Use Ctrl + D.

Recap + Bridge: write username opens a live, two-way terminal pipe to one logged-in user, closed with Ctrl + D and coordinated with who to find the target. This is the private half of inter-user talk; the next sub-section extends it to broadcast with wall and to discovery with who.

Real-world and domain connection: On multi-user servers, headless build machines, and early timesharing systems before Slack or Teams, write/wall were the sysadmin's coordination tools — a quick wall System going down in 5 minutes reaches every logged-in engineer without external dependencies. Today the same idea survives in tmux/screen messaging, DevOps jump hosts, and classroom lab servers where students share one machine. In systems programming, it illustrates the core UNIX idea that everything is a file — a terminal is just a writable file, and write is literally writing bytes to another user's terminal device file in /dev.

4.1.2 who and wall — Seeing Who Is Present and Broadcasting

Purpose: who answers "who is available to talk to?" and wall answers "how do I tell everyone at once?" Together they make write usable.

  • Inputs and outputs:
  • who — no required argument. Output columns: login name, terminal line (tty7, pts/0), login time/date, and sometimes remote host. Example: who → mary tty7 Sep 25 19:03.
  • who am i — shows only your own line, useful in a maze of terminals.
  • wall — reads either from its arguments or from standard input and writes to every logged-in user's terminal. Typical forms: wall then type message then Ctrl + D, or echo "reboot in 5" | wall, or wall message.txt.
  • wall often requires privileges on modern systems; historically any user could broadcast.

Worked example — discover then broadcast:

\$ who
jib   tty0  Sep 25 13:59
you   tty2  Sep 25 23:01
mary  tty7  Sep 25 19:03
\$ wall
System will reboot at 23:30 for maintenance. Please save work. (oo)
Ctrl-D
Broadcast Message from you@server (tty2) at 23:25 ...
System will reboot at 23:30 for maintenance. Please save work. (oo)

Steps: who reveals mary is on tty7. wall without arguments reads from keyboard until Ctrl + D, then the kernel delivers the same banner plus your text to every terminal including your own. Verifying: each user sees the same Broadcast Message ... header. The point Ctrl + D as EOF mirrors cat > file and sort — one convention reused everywhere.

Alternative single-line: echo "lab ends in 10" | wall achieves the same without interactive typing. Sense-check: if who shows zero others, wall still succeeds but only you see it — no error, just no audience.

Scope and assumptions:

  • who scope: Shows only currently logged-in sessions on this host. It does not show users connected via web apps or other hosts.
  • wall scope: Writes to every terminal whose mesg is y. Users with mesg n do not receive it, and on many modern distros only root may wall to avoid spam.
  • Breaks when: You confuse who (present users) with whoami/id (your own identity) or users (terse list). Each has different output shape.

Visual intuition: Imagine a server room with 6 terminals in a row; who lights up the 3 occupied seats (name tags above them, login time below). write draws one arrow from you to one lit seat; wall draws a fan of arrows from you to all lit seats simultaneously. Takeaway: discovery (who) must precede targeted talk (write), while wall skips targeting.

Pitfalls:

  • Thinking wall is private: Forgetting it hits everyone — including instructors — leads to accidental noise. Use write for one person.
  • Misreading who columns: The second column is the tty name needed for write mary tty7 disambiguation; ignoring it causes "logged in more than once" confusion.
  • Expecting Q to quit who: Q quits man and less, not who. who exits after printing; no pager involved.

Recap + Bridge: who discovers the audience, write talks to one, wall talks to all, all closed with the same Ctrl + D EOF idea. With communication covered, the lecture turns to the self-help tool that documents every other command: man.

Real-world: In production, who and wall (or its modern cousin shutdown -r +5 "message") coordinate maintenance windows on shared department servers and HPC clusters — a wall before reboot prevents lost lab work when dozens share one login node. The same pattern — enumerate presence then message — recurs in Slack's /who and Kubernetes kubectl get pods before kubectl exec.

4.2 Manual Pages — man and the GCC Example

4.2.1 man — The On-System Manual Pager

man stands for manual. For any command you want to understand in depth you rely on man. It shows the description, synopsis, and every option with its meaning. You navigate inside the pager and press Q to quit — Q indicates quit — and you return to the prompt.

4.2.2 GCC Manual as a Rich Example

A concrete illustration is man gcc. GCC is the GNU Compiler Collection, which compiles C and C++ files. Its manual page first gives a short description and then enumerates a long list of options and their significance. The point is that you do not need to search the internet for this detail. An offline Linux system already carries the same material that you would later find rendered as HTML online; the HTML is generated from these same man pages. When you are logged into a Linux machine the manual is immediately available. This also explains a note about write: it had no interesting options to illustrate, so the demonstration switches to gcc where many options make the manual page structure visible.

Worked example — man gcc as a rich manual page: Run man gcc and you see a short description of GCC — the GNU Compiler Collection that compiles C and C++ files — followed by a long enumerated list of options and their significance. The HTML you find online is generated from these same man pages, so an offline Linux machine already carries the material. Press Q to quit the pager and return to the prompt. Keywords: man gcc GCC GNU Compiler Collection compiles C and C++ description options significance HTML generated manual pages Q quit pager.

Purpose — man as on-system handbook: man opens the on-system manual pager for any command, showing description, synopsis, and every option. Navigation inside the pager and Q to quit are consistent patterns. Real-world: developers on air-gapped servers read GCC options offline via man, no internet needed.

Pitfalls: Confusing man write (few options) with man gcc (dozens) — the demo switches to gcc precisely because write had no interesting options to illustrate. Forgetting Q leaves you stuck in pager.

Recap + Bridge: man is the offline handbook and man gcc proves it with a rich option list. Next, where you stand in the filesystem matters: pwd and home placement.

4.3 Present Working Directory — pwd, Home Placement, and Hidden Startup Files

4.3.1 pwd — Print Working Directory

pwd stands for print working directory. It is often called present working directory and that phrasing is not wrong. It prints the absolute path of the directory you are currently in.

Examples shown in the session:

  • Immediately after login, pwd returns /home/ubuntu because that is the current working directory.
  • From there cd / followed by pwd returns / — you are in root.
  • Bare cd with no argument returns you to your home, and pwd again shows /home/ubuntu.
  • mkdir SP followed by cd SP and pwd shows /home/ubuntu/SP. Running ls in /home/ubuntu confirms that SP is one of the entries.

So ls and pwd complement each other: ls lists what is inside the current directory, pwd tells you where that current directory sits in the tree.

4.3.2 Where You Land on Login and the Hidden .bashrc File

Whenever you log into any system, the system places you in your home directory immediately. If you want to land elsewhere automatically, for example directly in a project folder, you do not need to type cd manually each time.

Every user home contains a hidden file named .bashrc. Hidden files are recognized because their name starts with a dot .. .bashrc is executed every time you log in. Opening it shows the script that runs at login. Putting a command such as cd /home/ubuntu/SP inside .bashrc will place you in that project directory right after login. The file is internal and normally not shown by plain ls; you will see why in the next section.

Understanding this matters for real work: shell startup files let you tailor the environment, and hidden dotfiles are the convention for configuration that should not clutter a normal listing.

Q: What else does ls show beyond regular files and subdirectories? A: By itself plain ls shows only regular files and subfolders. To see more — hidden entries, detailed metadata, sorting variations — you must add options. The long listing and the all flag are the first two to learn.

Worked example — pwd through a session: After login pwd shows /home/ubuntu. cd / then pwd shows / (root). Bare cd then pwd shows /home/ubuntu again. mkdir SP then cd SP then pwd shows /home/ubuntu/SP. ls in /home/ubuntu confirms SP appears. This shows ls lists contents while pwd tells where you are. Keywords: pwd shows home ubuntu root and SP directory after mkdir and cd.

Q: What else does ls show beyond regular files and subdirectories? A: By itself plain ls shows only regular files and subfolders. To see more — hidden entries, detailed metadata, sorting variations — you must add options. The long listing and the all flag are the first two to learn. Keywords: What else does ls show beyond regular files and subdirectories Plain ls shows only regular files and subfolders need options long listing and all flag.

Scope: pwd prints the absolute path of the current working directory, often called present working directory. Hidden file .bashrc starts with dot and is executed every time you log in; putting cd /home/ubuntu/SP inside auto-lands you there. Plain ls hides dotfiles; next section shows why.

Recap + Bridge: pwd locates you; ls lists around you; .bashrc automates where you land. Next is the full listing power of ls.

4.4 Listing Contents with ls — Meaning of . .. ~ and Every Common Option

ls is short for list. It lists the contents of the current directory — files and subdirectories or subfolders. Plain ls gives just names. The teaching value is in the options that reveal type, state, and history.

4.4.1 Long Listing with ls -l

ls -l — hyphen l for long — is long listing. It expands each entry into columns:

  1. Permissions string for user, group, and others. The first column encodes who can read, write, and execute that file or directory. The session notes deferring the full user-group-other model but tells you to remember that column one is permissions.
  2. Link count — how many links point to that inode. The session states it will not explain links yet.
  3. Owner user.
  4. Owner group — who has permission to work with the entry.
  5. Size.
  6. Time of creation or last modification.
  7. Name.

So a long line tells you not just what exists, but how big it is, who owns it, when it was touched, and what you are allowed to do with it. This is the form you use when permissions or sizes matter.

4.4.2 All Entries Including Hidden with ls -a

Hidden files in Linux are not hidden by an attribute but by naming convention: any file or folder whose name starts with a dot . is hidden. Examples in a typical home include .bashrc and .gnupg. Both regular files and directories can be hidden this way.

  • ls alone does not show these.
  • ls -a — a for all — shows everything including hidden. The output then includes entries such as ., .., .bashrc, .gnupg alongside visible folders.
  • ls -a -l or ls -al combines both: long detail for every entry including the dotfiles. In that combined view you can see . and .. themselves with their permission strings and other columns.

The distinction is visible directly: compare ls versus ls -a in the same directory and the extra dot-prefixed names appear.

4.4.3 The Special Directory Names . .. ~ and /

Four symbols form a shorthand for navigation and listing:

  • . — a single dot indicates the current directory. It means same directory, and it is hidden in the naming sense. Demonstration: pwd says /home/ubuntu, then cd . and pwd again still says /home/ubuntu. Nothing moved. Similarly ls . lists the contents of the current directory and is identical in result to plain ls.
  • .. — two dots indicate the parent directory. Demonstration: pwd shows /home/ubuntu, then cd .. moves to /home. Checking, /home is the parent of /home/ubuntu. Likewise ls .. lists the contents of the parent, not the current directory. It does not move you there; it only displays what is in the parent.
  • ~ — tilde, described as the left-and-top key before 1 that you get with Shift, indicates the user home directory. ls ~ shows the contents of the user home, in the example the Ubuntu home, and the output matches plain ls when you are already in that home. cd ~ lands in the user home. Bare cd with no argument does the same thing.
  • / — a single forward leaning slash is the root, the top level of the file system.

A common learner misinterpretation is to confuse .. with home or ~ with current. The correction repeated in the session is: . is current, .. is parent, ~ is user home, / is root. ls . is current, ls .. is parent, ls ~ is home.

Why two ways to go home, cd and cd ~? Historical usage: cd ~ existed first as the explicit way to say change to user home. Because people used it constantly, implementations added the shortcut that bare cd defaults to the user home. So both remain, doing the same job.

Combinations also make sense once the atoms are clear, though their printed output may look the same while the internal resolution differs:

  • ls .. — parent directory contents.
  • ls . — current directory contents.
  • ls ../. — parent directory followed by its current entry. When the current directory is /home/ubuntu/SP and its parent is /home/ubuntu, this resolves to the parent's contents.
  • ls ./.. — current directory followed by its parent. Same visible result in this tree, different traversal.
  • ls -R would be recursive listing of all subfolders, but the immediate point is that dot and dot-dot are composable path components separated by /.

4.4.4 Sorting, Size, Inode, Reverse, Recursive and Human-Readable Options

Beyond l and a, the session walks through the manual page for ls and demonstrates each flag live:

  • ls -t — t for sort by modification time, newest first. Example timestamps such as 17:58, 58:53 etc. become ordered with the most recent at the top. Plain ls or ls -l without t is sorted by name, not by time; adding t reorders by time.
  • ls -S — capital S sorts by file size, largest first. Lowercase s does something different: ls -s prints the allocated size of each file in blocks. Capital S sorts, lowercase s prints. This pair is a frequent confusion point.
  • ls -r — r for reverse. If ls shows F1 to zombie in name order, ls -r shows zombie to F1.
  • ls -R — capital R for recursive. It descends into every subdirectory and lists their contents as well, for example showing /Desktop with nothing, /Music with users.txt, /OS with its files, /Pictures empty, and so on. It is the way to list an entire tree without entering each folder manually.
  • ls -i — i for inode number. An inode number uniquely identifies a file on the file system. ls -i prints just the inode number alongside each name, for example F1 with its number, F2 with its number. The detailed inode discussion is deferred but the uniqueness property is stated.
  • ls -h — h for human readable. With long listing it prints sizes in readable units rather than raw blocks. The manual describes it as human readable sizes.
  • Combinations are normal: ls -al, ls -lah, ls -l -a -i and so on.

Real-world: In everyday work you combine these without thinking — ls -lah for all plus human sizes plus long detail, ls -lt to find what you just edited, ls -R to audit a project tree. The manual page man ls documents near a dozen variants such as --classify, --format, --sort and the session encourages reading it directly because details like -h versus no header have changed over versions.

Q: What option shows files of a specific type? Is it ls -lt? What does a mean? A: Not lt. ls -a is the flag for all, including hidden. ls -t sorts by time, ls -l is long. You identify hidden versus non-hidden by the leading dot in the name.

Worked example — sorting and inode options: ls -t sorts by modification time newest first (timestamps 17:58 etc.), ls -S sorts by file size largest first, ls -s prints allocated size in blocks (different from capital S), ls -r reverses name order (F1..zombie becomes zombie..F1), ls -R recursively lists every subdirectory (Desktop, Music, OS, Pictures), ls -i prints inode number uniquely identifying a file, ls -h prints human readable sizes with long listing. Combinations like ls -al, ls -lah, ls -l -a -i are normal. Keywords: ls sorting time newest first size largest first reverse recursive inode human readable options. Also ls long listing permissions link owner group size time name seven columns. Also ls all hidden dotfiles including dot and dot dot hidden identification. Also cd dot stays same directory cd dot dot moves to parent home and tilde home demonstration.

Q: What option shows files of a specific type? Is it ls -lt? What does  mean? A: Not lt. ls -a is the flag for all, including hidden. ls -t sorts by time, ls -l is long. You identify hidden versus non-hidden by the leading dot in the name. Keywords: What option shows files of specific type is it ls lt what does a mean Not lt ls minus a flag for all including hidden identified by leading dot.

Q: Confusing dot current versus dot dot parent versus tilde home? A: Correction: . is current ( cd . stays in /home/ubuntu, ls . same as ls), .. is parent (cd .. from /home/ubuntu goes to /home, ls .. lists parent), ~ is user home (ls ~ shows Ubuntu home, cd ~ same as bare cd), / is root. Two ways home cd and cd ~ remain because cd ~ was original explicit form and bare cd was added for convenience. Keywords: Confusing dot current versus dot dot parent versus tilde home leads to inference exercise correction dot current parent tilde home inference.

Q: Why does ls -s versus ls -S confuse beginners? A: ls -s prints allocated blocks per file, ls -S sorts by size largest first. Capital S sorts, lowercase s prints. Keywords: ls minus s prints allocated blocks versus capital S sorts by size frequent confusion.

Pitfalls: Thinking ls alone shows hidden files — it does not, need -a. Confusing .. with home or ~ with current. Missing space in cd .. fails on Linux (works on Windows). Using ls -s when you meant ls -S.

Recap + Bridge: Long -l reveals permissions and metadata, -a reveals hidden dotfiles, . .. ~ / are composable navigation atoms, and -t -S -r -R -i -h cover time, size, reverse, recursive, inode, human readable. Exam note: time, S size, reverse, R recursive, i inode.

4.5 Creating Directories and Files — mkdir and touch and a Concrete Hierarchy

4.5.1 mkdir — Make Directories

mkdir stands for make directories. It creates directories. The syntax is mkdir followed by one or more names. Each name becomes a parameter and a separate folder is created.

You can create several siblings at once: mkdir dir1 dir2 dir3 creates three separate folders inside the current directory with a single command. This is faster than invoking mkdir three times.

4.5.2 A Practice Hierarchy Built Live

The session builds a sample hierarchy under the user home to exercise mkdir, cd, and touch together. The structure, using black for folders and red for files in the slide, is:

  • sim1/ — top project folder under /home/ubuntu
  • WI_Bangalore/ — sibling of bits and Wipro inside sim1
  • STD1/
  • STD2/
  • bits/
  • Goa/ — contains paper.doc only here
  • Hyderabad/ — empty
  • Pilani/ — empty
  • Wipro/
  • SIM/ — contains student.doc
  • ways/ — written in the session as ways / WAYS / waste in spoken variants, containing student.doc

Live steps shown:

  1. From home, mkdir sim1 or multiple names at once, then ls confirms sim1 appears.
  2. cd WI_Bangalore then mkdir STD1 STD2 to make two siblings inside it.
  3. Come back with cd .., then cd bits and mkdir Goa Hyderabad Pilani — three siblings. ls back in the parent confirms all three.
  4. Back to parent, cd Wipro then mkdir ways SIM.
  5. Verify with ls -R from sim1 which recursively lists Desktop, Music, OS, Pictures examples and then the sim1 tree, showing bits/Goa with paper.doc and bits/Hyderabad, bits/Pilani empty, and Wipro/SIM with student.doc and Wipro/ways with student.doc.

The point of the exercise is to create the identical tree on your own machine and share a snapshot taken recursively so the structure is visible without tree graphics. Plain ls -R output interleaves folder headers with their contents, which is how you confirm the shape.

4.5.3 touch — Create Empty Files

touch creates an empty file with zero bytes when the file does not exist. Example: touch tmp then ls -l shows tmp with size 0.

In the hierarchy, touch populates document slots:

  • Inside Wipro/ways, touch student.doc creates the file.
  • Inside Wipro/SIM, touch student.doc again creates the parallel file.
  • Inside bits/Goa, touch paper.doc alone populates only that campus folder.
  • Later a task asks to create info.txt inside WI_Bangalore. The correct form is touch WI_Bangalore/info.txt without entering that directory first.

The session also notes that touch with an explicit path both creates and sets an empty file you can later verify with ls -lR.

Student exchange on listing those files without entering each folder:

Q: If I want to check the contents of both Wipro/ways and Wipro/SIM from the parent without individually entering each folder, what should I give? A: Use recursive listing. ls -R or ls with the directory names as arguments while staying in Wipro shows first the two folder names present in Wipro and then the contents inside SIM and the contents inside ways. You do not need to cd into each.

Worked example — mkdir siblings and touch files: mkdir dir1 dir2 dir3 creates three separate folders in one command. In live hierarchy: from home mkdir sim1, cd WI_Bangalore then mkdir STD1 STD2 makes two siblings, cd bits then mkdir Goa Hyderabad Pilani makes three, cd Wipro then mkdir ways SIM makes two. ouch tmp then ls -l shows size 0. Then ouch student.doc in Wipro/ways and Wipro/SIM, ouch paper.doc only in its/Goa, and ouch WI_Bangalore/info.txt without cd first. Verify with ls -R from sim1 showing Desktop Music OS Pictures examples and sim1 tree with bits/Goa paper.doc and Wipro ways/SIM student.doc. Keywords: mkdir multiple arguments creates three siblings WI_Bangalore STD1 STD2 and bits Goa Hyderabad Pilani. Also touch creates zero byte file tmp and student doc in Wipro ways and SIM and paper doc in Goa.

Q: If I want to check the contents of both Wipro/ways and Wipro/SIM from the parent without individually entering each folder, what should I give? A: Use recursive listing. ls -R or ls with the directory names as arguments while staying in Wipro shows first the two folder names present in Wipro and then the contents inside SIM and the contents inside ways. You do not need to cd into each. Keywords: How to check contents of both Wipro ways and SIM without entering each folder Use recursive listing ls minus R shows folders and their contents without cd.

Scope: mkdir creates directories, ouch creates empty zero-byte files when missing (and updates timestamps when existing). Combinations like ls -R audit whole tree without entering each folder.

Recap + Bridge: mkdir builds the skeleton with multiple arguments at once, ouch populates files, ls -R verifies the tree. Next is how to move inside that tree with cd and paths.

4.6 Navigating with cd — Syntax Rules and Absolute versus Relative Paths

4.6.1 Command-Argument Separation

Every shell command expects the first word to be the command and the following words to be parameters or options. Writing a path before the command fails: typing W_Bangalore/touch/info makes the shell say W_Bangalore is not a command. The correct order is touch W_Bangalore/info.txt — command first, then path.

A second syntax rule: there must be a space between cd and its argument. cd .. with a space is correct in Linux. cd.. without a space is an error in Linux, though it happens to work in Windows. This is deliberate in Unix design: the command and its parameter are distinct tokens.

4.6.2 cd Variants and What They Do

  • cd with no argument — goes to the user home directory, for example /home/ubuntu. This holds wherever you are, even if you are nested ten levels deep.
  • cd ~ — ~ is the user home directory, so cd ~ is identical to bare cd in effect and is the older explicit form.
  • cd . — dot is current directory, so you stay where you are. pwd before and after shows no change.
  • cd .. — dot-dot is parent. From /home/ubuntu it moves you to /home. /home is the parent of /home/ubuntu.
  • cd / — root.
  • cd /home/ubuntu/sim1 — absolute form to a deep destination.
  • cd sim1/bits/Goa — relative form from home to the same destination when sim1 is under the current home.

The session stresses precise language: bare cd and cd ~ return to the user home, which is /home/ubuntu for that user, not /home itself. /home is the parent that holds all user homes.

4.6.3 Absolute versus Relative Paths — Definitions and Three Variations

The distinction is central and the slide quoted in the session states it explicitly:

  • Absolute path describes the location of a file or directory starting from the top level of the file system, which is root. It always starts with the forward leaning slash /. Irrespective of where you are, the absolute path to a destination is the same. Example from the lecture: /home/ubuntu/sim1/bits/Goa from any working directory still points to Goa. In scripts this stability is why absolute paths are preferred.
  • Relative path describes the location relative to the present working directory. It never starts with /. Its spelling depends on where you are. Example: from user home, sim1/bits/Goa reaches Goa. From root you would need the absolute form.

Three variations demonstrated to reach the same Goa folder:

  1. Relative from user home: cd sim1/bits/Goa. The argument does not start with /; it is resolved starting at the current directory which is /home/ubuntu.
  2. Absolute from root: cd /home/ubuntu/sim1/bits/Goa. First / is root, then home, then user home ubuntu, then sim1, bits, Goa.
  3. Relative via tilde from user home: cd ~/sim1/bits/Goa. ~ expands to user home, then the rest is appended. In this tree this is the same as variation 1 because ~ is /home/ubuntu.

The first and third are both relative — both are computed from a starting point that is not root — while the second is absolute and never changes even if you cd elsewhere first. The professor reads the slide to make the wording stick: absolute never starts without / and always starts with /, relative never starts with /.

Real-world: In industry you choose based on stability. For a script that must work no matter where the user invoked it, use absolute. For a quick interactive move or for portable project commands that should work on any machine where the project is checked out at a different root, use relative.

Q: Why have both cd and cd ~ if they do the same thing? Why not keep just one? A: cd ~ was the original explicit form — ~ meaning user home made the intent obvious. As people used the operation constantly, the shorter bare cd defaulting to home was added for convenience. Both remain so scripts and habits that use either still work.

Exam note: Expect to write both forms for the same destination and to label which is absolute and which is relative, explaining why absolute starts with / and relative does not.

Worked example — absolute versus relative to Goa: From any directory cd /home/ubuntu/sim1/bits/Goa is absolute (starts with / root, then home ubuntu sim1 bits Goa) and never changes. From user home /home/ubuntu, cd sim1/bits/Goa is relative (never starts with /, resolved from current directory). cd ~/sim1/bits/Goa is also relative via tilde expansion (~ is /home/ubuntu). Bare cd and cd ~ both go to user home /home/ubuntu not /home. cd . stays, cd .. goes to parent /home, cd / goes to root. Keywords: absolute path from root slash home ubuntu sim1 bits Goa versus relative sim1 bits Goa and tilde variant slash home ubuntu sim1 bits Goa.

Q: Why have both cd and cd ~ if they do the same home action? A: cd ~ was the original explicit form — ~ meaning user home made the intent obvious. As people used the operation constantly, the shorter bare cd defaulting to home was added for convenience. Both remain so scripts and habits that use either still work. Keywords: Why have both cd and cd tilde if they do same home action cd tilde was original explicit form for user home bare cd added later for convenience. Historical evolution retains both.

Q: Why does cd.. fail on Linux but work on Windows? A: Linux requires a space between cd and .. because command and parameter are distinct tokens. cd .. with space is correct; cd.. without space is parsed as a command name that does not exist. Windows parser tolerates missing space, Linux does not. Keywords: Need space between cd and dot dot cd dot dot without space error on Linux works on Windows.

Pitfalls: Writing W_Bangalore/touch/info puts path before command — shell says W_Bangalore is not a command. Correct is ouch W_Bangalore/info.txt command first. Forgetting leading / makes absolute look relative, and starting relative with / makes it absolute by accident.

Recap + Bridge: Absolute starts with / from root and is stable; relative never starts with / and depends on present. cd .. needs a space. Next session turns these definitions into live tasks where students are corrected.

4.7 Guided Navigation Exercises and Reasoning

The session turns the definitions into live tasks with student attempts and corrections. These exchanges are the clearest way to learn the pitfalls.

4.7.1 From STD1 to ways — Absolute and Relative

Prompt: you are currently in STD1 — clarified as sim1, effectively /home/ubuntu/sim1/WI_Bangalore/STD1 or sim1/WI_Bangalore/STD1 — change to ways which lives at sim1/Wipro/ways using both an absolute and a relative command.

Student attempts discussed:

  • Absolute attempt: cd /home/ubuntu/sim1/Wipro/ways — correctly absolute because it begins with / representing root, then home, user home, sim1, Wipro, ways. It works from anywhere and does not change.
  • Relative attempt that was marked incorrect: cd ~/sim1/Wipro/ways or cd sim1/Wipro/ways given while already inside sim1/WI_Bangalore/STD1. The reasoning correction is that while ~/sim1/... is technically a valid path from that starting point when expanded, a relative answer is expected to start from the present working directory, not from the user home. The relative path anchored at the actual present directory would be something like cd ../../Wipro/ways or cd /home/ubuntu logic aside, the point emphasized is that a true relative answer must be expressed as movement from where you are now via .., not as a fresh path from home. Solutions that ignored the present directory and re-anchored at home were called wrong for the purpose of the question even though the shell would accept them.

A correct relative answer shown: cd ../../Wipro/ways — .. to WI_Bangalore, another .. to sim1, then Wipro/ways. Another correct variant: cd /Wipro? No — cd /Wipro/ways was shown as the minimal relative that works if you interpret the slide's relative as from sim1 ( cd Wipro/ways ). The teaching correction is that relative must be relative to the present, so your path must begin with navigation from that present.

A related attempt using cd .. chain was accepted as relative: cd ../../../sim1/Wipro/ways from a deeper start still counts as relative because it begins with ...

4.7.2 Creating a File Under ways from Pilani Using Relative Path

Prompt: your present working directory is Pilani which is sim1/bits/Pilani. Create a file named after your bits ID, for example bitsID.doc, under the ways directory using a relative path.

The reasoning path needed: from Pilani, .. is bits, another .. is sim1, then Wipro/ways. So the relative path to the destination file is ../../Wipro/ways/bitsID.doc and the full command is touch ../../Wipro/ways/bitsID.doc. The session notes that understanding what . and .. expand to at each step is essential, and that tilde ~ would be wrong here because the task explicitly asks for relative to the present, not from home.

4.7.3 Absolute Creation Under STD1 from Sim

Prompt: assume you are in sim folder and you must create a file under STD1 using absolute path with your bits ID.

Correct pattern shown by peers: touch /home/ubuntu/sim1/WI_Bangalore/STD1/bitsID.doc or for the demo name touch /home/ubuntu/sim1/WI_Bangalore/STD1/bitsID.txt. Feedback given: Supraja's attempt was marked wrong because it omitted the root leading / required for absolute. Another peer missed the space between touch and the path — touchWI_Bangalore without a space is parsed as a command name that does not exist. Absolute always starts with /, includes home, the user directory, sim1, WI_Bangalore, STD1, and then the filename.

4.7.4 Where Does mkdir ./../newdir Create from Pilani?

Prompt: assume you are in Pilani under bits under sim1. If you run mkdir ./../newdir where will newdir be created?

Student split between bits and sim1. Resolution: break the argument into components. . is current which is Pilani. .. is parent which is bits. So ./.. from Pilani resolves to bits. Appending /newdir creates the new directory inside bits. If the command had been mkdir ../../newdir it would have been .. to bits, another .. to sim1, and creation inside sim1. So the answer is bits, not sim1. Two peers who said bits were correct.

Q: If mkdir argument is ../.. would it go to sim? A: Yes. Each .. moves one level up. From Pilani, one .. is bits, two .. is sim1. The given command has only one .. after the dot, so it stops at bits.

Worked example — STD1 to ways and Pilani exercises: Prompt: in STD1 which is /home/ubuntu/sim1/WI_Bangalore/STD1 change to ways at sim1/Wipro/ways. Absolute: cd /home/ubuntu/sim1/Wipro/ways correctly absolute because it begins with / root. Relative must start from present: cd ../../Wipro/ways — .. to WI_Bangalore, another .. to sim1, then Wipro/ways. cd ~/sim1/Wipro/ways was marked incorrect for the question because it re-anchors at home not present. Second prompt: present is Pilani (sim1/bits/Pilani) create itsID.doc under ways via relative: ouch ../../Wipro/ways/bitsID.doc (.. to bits, .. to sim1). Third: where does mkdir ./../newdir create from Pilani? ./.. from Pilani resolves to its (.. is parent, . is current Pilani) so newdir inside its, not sim1. mkdir ../../newdir would go to sim1. Keywords: from STD1 to ways absolute slash home ubuntu and relative dot dot Wipro ways correction. Also from Pilani to ways relative touch dot dot Wipro ways bitsID doc. Also mkdir dot slash dot dot slash newdir from Pilani creates in bits not sim1. Also Relative path must start from present working directory not re anchor at home correction of STD1 to ways attempt.

Q: If mkdir argument is ../.. would it go to sim? And where does mkdir ./../newdir create from Pilani — bits or sim1? A: Yes each .. moves one level up. From Pilani, one .. is its, two .. is sim1. The given mkdir ./../newdir has only one .. after the dot, so it stops at its. So ../.. would go to sim1, ./../newdir creates in its not sim1. Trigger mkdir dot slash dot dot newdir where created bits or sim1 resolution dot is current Pilani dot dot is parent bits so newdir inside bits. Keywords: If mkdir argument is dot dot dot would it go to sim Yes each dot dot moves one level up from Pilani one to bits two to sim1 single stops at bits.

Q: Why was cd ~/sim1/Wipro/ways judged wrong when inside STD1 even though shell accepts it? A: Relative path must start from present working directory not re-anchor at home. From /home/ubuntu/sim1/WI_Bangalore/STD1, correct relative is ../../Wipro/ways via .. steps, not a fresh path from home. The exam expects movement from where you are. Keywords: Relative path must start from present working directory not re anchor at home correction of STD1 to ways attempt.

Pitfalls: Ignoring present directory and re-anchoring at ~ or sim1 when question asks for relative from STD1 or Pilani. Confusing ./../newdir with ../../newdir — one .. stops at its, two .. reaches sim1. Missing space in ouch command or omitting leading / for absolute.

Recap + Bridge: Relative means from where you stand via ..; absolute means from /. Counting .. steps is the exam trap. After navigation, editing: old ed versus quick ouch.

4.8 Creating and Editing Files — ed Versus touch

4.8.1 touch — Quick Empty File Creation

touch is presented as the easy recent way to create an empty file. touch filename makes a zero-byte file. In the demonstration touch tmp and then ls -l shows size 0.

4.8.2 ed — The Classic Buffer Editor Workflow

ed is introduced as the older editor family, available long before touch became common. Creating a file with ed requires several steps in sequence:

  1. ed sample.txt — invoke the editor on the desired filename. If the file does not exist it reports no such file or directory but still opens the buffer.
  2. a — for add. This enters input mode where subsequent lines are collected into the buffer.
  3. Type the content, for example hello. I am typing things in a new file.
  4. . on a line by itself — dot stops adding text.
  5. w sample.txt — write. This writes the buffer contents into the named file.
  6. q — quit the editor.

Demonstration shows ed sample.txt, then a, then text, then ., then w sample.txt, then q, then cat sample.txt displays hello. I am typing things in a new file. The point is that until w is given the text lives only in the editor buffer; w filename persists it.

4.8.3 Choosing Between touch and ed

Comparison made in the session: touch is very new — described as about five or six years in the surrounding narrative — and was not part of the old family of commands. ed belongs to the old family. For simple empty creation touch is preferred; for typed content the older ed shows the buffer-write-quit model that later editors inherit.

Exercise given: create a file letter.doc in folder1 using ed. The expected sequence is a to add, . to stop, w folder1/letter.doc or w letter.doc depending on your present directory, then q to quit. The four letters a, ., w filename, q summarize the model.

Q: Can I create a file as W_Bangalore/touch/info? A: No. The first word must be the command. W_Bangalore is not a command, so the shell reports not a command. The correct order is touch W_Bangalore/info.txt — command touch first, then the path as its parameter.

Q: Does ed warn before overwriting an existing file? If I create the same name again will it ask? A: No warning. Demonstrated with touch temp then ed overwriting temp with yay I am overriding, then ., w temp, q, and cat temp now shows the new single line. It just overwrites. Only access permissions can prevent writing; otherwise the editor assumes you intend the write. The session notes that permission-based protection will be covered later and is premature now.

Worked example — ed versus touch: ouch tmp then ls -l shows size 0 zero bytes. ed sample.txt workflow: ed sample.txt (reports no such file if missing but opens buffer),  to add, type hello. I am typing things in a new file., . on a line by itself to stop, w sample.txt to write buffer to file, q to quit, then cat sample.txt shows the line. Second example: ouch temp then ed temp with  then yay I am overriding then . then w temp then q then cat temp shows the single new line — it just overwrites, no warning. Keywords: ed sample txt add dot write quit creates hello typing new file then cat shows content. Also ed overwriting temp with yay overriding shows no warning only permissions restrict.

Q: Can I create a file as W_Bangalore/touch/info? A: No. The first word must be the command. W_Bangalore is not a command, so the shell reports ot a command. The correct order is ouch W_Bangalore/info.txt — command ouch first, then the path as its parameter. Trigger order of command and path touch must be first word path second not folder slash touch resolution: No first word must be command W_Bangalore is not command correct is touch path. Keywords: Can I create file as W_Bangalore slash touch slash info with touch not first No first word must be command W_Bangalore is not command correct is touch path.

Q: Does ed warn before overwriting an existing file? If I create the same name again will it ask? A: No warning. Demonstrated with ouch temp then ed overwriting emp with yay I am overriding, then ., w temp, q, and cat temp now shows the new single line. It just overwrites. Only access permissions can prevent writing; otherwise the editor assumes you intend the write. Keywords: Does ed warn before overwriting existing file same name again No warning overwrites directly demonstrated temp yay overriding only permissions can prevent.

Scope: ouch is modern quick empty creation; ed is classic buffer editor with  . w q model that later editors inherit. ed shows buffer model: text lives only in buffer until w filename persists it.

Recap + Bridge: ouch for empty, ed for typed via  . w q, and ed overwrites silently. Next is file display and combining.

4.9 Displaying and Combining Files — cat and Printing with pr

4.9.1 cat — Display and Concatenate

cat is both a display and a concatenation tool. Beyond cat file to show contents, cat file1 file2 > file3 concatenates. The session builds two files with ed to illustrate:

  • Preparation: using ed, add this is first line then . then w sim1/Wipro/ways/student.doc, similarly this is my second line written to sim1/Wipro/SIM/student.doc. Then cat shows each file individually.

Then the task: create a new document named final.doc under Wipro whose content is the concatenation of student.doc under ways followed by student.doc under SIM, using absolute paths.

Correct construction uses cat with redirection: cat /home/ubuntu/sim1/Wipro/ways/student.doc /home/ubuntu/sim1/Wipro/SIM/student.doc > /home/ubuntu/sim1/Wipro/final.doc. The > takes the combined stdout of the two cats and writes it into the destination absolute path. The session initially tries cat to combine and shows the concatenation working.

4.9.2 pr — Formatting for Printing

pr is introduced for printing preparation. man pr says pr converts text files for printing. Since no printer is attached the demo skips actual printing, but notes key behaviors: every page has 66 lines, date and time header, multi-column options. Examples: pr file1 file2 for basic printing format, pr -3 file to print in three columns, pr -j to merge full lines without column alignment, pr -m to print all files in parallel one in each column. The takeaway is that pr formats rather than just dumps like cat.

Worked example — cat concatenate and pr format: Using ed, add his is first line then . then w sim1/Wipro/ways/student.doc, similarly his is my second line to sim1/Wipro/SIM/student.doc. Then cat /home/ubuntu/sim1/Wipro/ways/student.doc /home/ubuntu/sim1/Wipro/SIM/student.doc > /home/ubuntu/sim1/Wipro/final.doc concatenates with > redirection. cat shows each file individually. For printing, pr converts text for printing: every page 66 lines, date time header, pr -3 file prints three columns, pr -j merges lines, pr -m prints files in parallel one per column. man pr confirms. Keywords: cat concatenates student doc ways and SIM into final doc using absolute paths with redirection.

Scope: cat displays and concatenates (cat file1 file2 > file3), pr formats for printing (66 lines, headers, columns) rather than just dumping. No printer needed for demo but behavior is documented.

Recap + Bridge: cat merges, pr paginates. Both prepare content that is then redirected.

4.10 Redirection > and Append >> — Building, Redirecting, and Updating Files

Two redirection symbols are contrasted:

  • > — single greater-than — writes stdout into a file, creating the file if needed or overwriting it if it exists.
  • >> — two greater-than — appends to a file, updating its contents without discarding what was already there.

Three concrete uses in the session:

4.10.1 Capturing ls Output

Assume your present working directory is Goa which is sim1/bits/Goa. Store the result of ls -l -a -i into a file results.txt in Goa itself.

Steps: cd sim1/bits/Goa to ensure present is Goa, then ls -l -a -i > results.txt. The command generates an output but the output is not printed on the screen; it is redirected into results.txt. Verifying with cat results.txt shows the long, all, inode listing that was generated.

4.10.2 Concatenation into a Final Document

As above, cat file1 file2 > newfile.txt uses > to write the concatenated contents into a new file. Example with absolute paths all three — two sources and the destination /home/ubuntu/sim1/bits/newfile.txt — succeeds only when each absolute directory actually exists; an early attempt failed with no such file or directory because the intermediate path /home/bits does not exist until written correctly as /home/ubuntu/sim1/bits.

4.10.3 Updating Versus Overwriting info.txt — Relative Path Pitfall

Prompt: you are in bits which is /home/ubuntu/sim1/bits. You wish to update the contents of info.txt which is present in WI_Bangalore — note WI_Bangalore is a sibling of bits inside sim1, not a child of home or root.

Three candidate commands are discussed, all claimed to use relative path:

  1. /WI_Bangalore/... with leading slash — wrong because leading / means root. Under root WI_Bangalore does not exist.
  2. ~/WI_Bangalore/... with tilde — wrong because ~ is user home /home/ubuntu, and under that WI_Bangalore does not exist. WI_Bangalore is under sim1, not directly under home.
  3. The third variant also with tilde suffers the same location error.

So none of the three paths are correct in terms of location, and the correct missing path would need ../WI_Bangalore/info.txt from bits — .. to sim1, then WI_Bangalore/info.txt.

Beyond location, the update intent matters: the question says update the contents, not rewrite. To append you must use >> not >. A single > would replace the file; two >> appends.

Q: Which of the three options correctly updates info.txt using relative path? Several peers split between the second and third, one says none. A: None is correct for the location, because all three miss the sim1 component and misplace WI_Bangalore. For the operation, updating requires >>. An update would look like echo new line >> ../WI_Bangalore/info.txt from bits, using .. to reach sim1 first and >> to append.

Exam note: Expect traps of this form — a path that looks plausible but fails because WI_Bangalore is not under root or not directly under ~, and a symbol choice that tests whether you know append is >> while write is >.

Worked example — redirection pitfalls: From Goa which is sim1/bits/Goa, ls -l -a -i > results.txt generates output but not printed; cat results.txt verifies the long all inode listing was redirected. Second: cat file1 file2 > newfile.txt with absolute paths fails with o such file or directory when intermediate path /home/bits does not exist until correctly /home/ubuntu/sim1/bits. Third: from its which is /home/ubuntu/sim1/bits updating info.txt in WI_Bangalore (sibling under sim1 not child of home or root) none of three options /WI_Bangalore/... (root) ~/WI_Bangalore/... (home) are correct because WI_Bangalore lives under sim1. Correct missing path is ../WI_Bangalore/info.txt (.. to sim1). Update needs append >> not overwrite >; echo new line >> ../WI_Bangalore/info.txt appends. Keywords: ls -l -a -i redirected with greater into results txt in Goa and verified with cat. Also info txt update requires append two greater symbols none of three relative paths correct missing sim1. Also Single greater writes overwrite double greater appends update distinction for info txt. Also leading slash means root tilde means home WI_Bangalore under sim1.

Q: Which of the three options correctly updates info.txt using relative path? Several peers split between the second and third, one says none. A: None is correct for the location, because all three miss the sim1 component and misplace WI_Bangalore. For the operation, updating requires >>. An update would look like echo new line >> ../WI_Bangalore/info.txt from its, using .. to reach sim1 first and >> to append. Trigger three options slash WI versus tilde WI versus tilde WI for info txt from bits resolution none correct missing sim1 component correct is dot dot WI_Bangalore double greater append. Keywords: Which of three options correctly updates info txt using relative path from bits None is correct all miss sim1 component and misplace WI_Bangalore update needs double greater append.

Q: When to use > versus >>? A: Single > writes stdout into a file, creating or overwriting. Double >> appends without discarding. Question says update not rewrite, so must use >>. Keywords: Single greater writes overwrite double greater appends update distinction for info txt.

Pitfalls: Using > when you need >> loses history. Using leading / for relative or ~ for a sibling under sim1 misplaces file. Forgetting directory must exist before absolute cat redirection.

Recap + Bridge: > creates or overwrites, >> appends; location needs ../WI_Bangalore not /WI_Bangalore or ~/WI_Bangalore. Next is copying and inspecting with cp and stat.

4.11 Copying with cp and Statistics with stat

4.11.1 cp — Copy Options and Their Behaviors

cp copies contents from a source file to a destination file. It requires two parameters: source and destination, as in cp file1.doc file2.doc.

Demonstrated options, each with meaning:

  • cp -i source destination — i for interactive. Prompts before overwriting. Example cp -i results.txt paper asks Do you want to overwrite? If you answer yes it overwrites; if no it keeps the destination. This guards against accidental overwrite.
  • cp -p — p for preserve. Preserves mode, ownership, and timestamps of the source as is in the destination.
  • cp -f — f for force. If an existing destination file cannot be opened, remove it and try again. Described as forceful copy.
  • cp -R — capital R for recursive. Copies directories recursively. This copies a directory and all its contents.
  • cp -u — u for update. Copies only when the source file is newer than the destination file, or when the destination is missing. If the destination is newer, no copy happens.
  • cp -n — n for no overwrite. Does not overwrite an existing file. This stops you from accidentally overwriting.
  • cp -v — v for verbose. Prints informative messages about what is being done.
  • Additional options for symbolic links are mentioned but skipped because links have not been introduced yet, and the session says they will not appear in the immediate assessment.

The worksheet tasks repeat these: create two files with this is first file and this is second file as contents, then try cp -u in both time orders to see whether the update happens depending on which is newer.

4.11.2 stat — File Statistics Field by Field

stat gives statistics of a file. Example stat results.txt prints:

  • File name.
  • Size on disk and number of blocks consumed, plus the I/O block size.
  • File type — regular file versus device file or character file. At this stage treat it as regular file; device details are deferred.
  • Device ID.
  • Inode number — the same unique number seen with ls -i — and how many links it has.
  • Access permissions for user, group, and others.
  • User ID and group ID — both 1000 in the demo because the file belongs to the ubuntu user.
  • Three timestamps: access, modify, and change. The session explicitly says the difference between modify and change is subtle and will be clarified later; for now just note that they are distinct and you should try the commands to observe the difference.

Understanding stat lets you see the inode behind a name and the metadata that ls -l summarizes.

Worked example — cp options and stat fields: cp requires source and destination: cp file1.doc file2.doc. Options: cp -i interactive prompts Do you want to overwrite? yes overwrites no keeps; cp -p preserves mode ownership timestamps; cp -f force removes destination if cannot open and tries again; cp -R recursive copies directories; cp -u update copies only when source newer or destination missing; cp -n no overwrite never overwrites; cp -v verbose prints what is done. Worksheet: create his is first file and his is second file then try cp -u both orders to see time dependence. stat results.txt fields: File name, Size on disk and blocks consumed plus I/O block size, File type regular versus device character, Device ID, Inode number same as ls -i and link count, Access permissions for user group others, UID GID both 1000 for ubuntu user, three timestamps access modify change — modify versus change subtle deferred. Keywords: cp interactive prompts before overwrite preserve mode force recursive update no overwrite verbose options. Also stat results txt shows size blocks IO block inode permissions UID GID access modify change times.

Scope: cp copies file contents, not directories unless -R. Symbolic link options skipped until links introduced. stat reveals inode and metadata that ls -l summarizes.

Recap + Bridge: cp guards (-i -n -u) and preserves (-p -v -R -f), stat audits. Next is relocation and deletion: mv, mdir, m.

4.12 Moving and Removing — mv, rmdir, and rm

4.12.1 mv — Move

mv physically moves a file or directory from a source folder to a destination folder. Replace the word place with folder. Example mv results /home/ubuntu moves the file results into the user home.

Option mv -i — i for interactive — should ask before moving. Demonstration with mv -i from the current directory to home showed that in this environment it did not prompt, but the file still moved: checking the current directory shows it is no longer there, checking the home shows results.txt now present there. rm -i contrastingly does prompt.

4.12.2 rmdir — Remove Empty Directories

rmdir is remove directory but only for empty directories. It takes the directory name as a parameter and removes it only if it contains no files or subfolders. This restriction is intentional.

4.12.3 rm — Remove Files and Recursive Deletion

rm removes a single file. Examples:

  • rm -i paper.doc — i for interactive — asks whether you want to remove the file. Answering no keeps it; yes removes. This was shown to work.
  • rm -R — capital R for recursive — deletes all files in all subdirectories. Combined with f for force, rm -R -f or rm -rf deletes everything under the current working directory including folders, subfolders, and sub-subfolders without further prompting. This is forceful deletion, and the session warns to use it deliberately.
  • rm -f also allows forced removal even if the file is write-protected, though the core teaching is recursive plus force.

Student interaction at the end clarifies a common confusion:

Q: rmdir did not work when the directory had folders and files inside. Can we remove a directory if it is not empty? A: Not with rmdir. rmdir only removes empty directories. To delete a directory even if it is not empty you need the options of rm, specifically the recursive and forceful form rm -R and rm -f. The exact command for non-empty directory removal is promised for the next class, but the principle — rmdir for empty, rm -R -f for everything — is established now.

Exam note: Expect to distinguish rmdir versus rm -R, and to know that rm -i prompts while rm -f forces.

Worked example — mv, rmdir, rm: mv results /home/ubuntu physically moves file to user home. mv -i should ask before moving but demo did not prompt yet file still moved — m -i does prompt contrast. mdir removes only empty directories: mdir dirname succeeds only if no files/subfolders. m paper.doc removes single file; m -i paper.doc asks yes removes o keeps; m -R recursive deletes all files in all subdirectories, m -R -f or m -rf deletes everything under current without prompting including folders subfolders force even if write-protected. Warning to use deliberately. Keywords: mv moves file to home rm interactive prompts rm recursive force deletes tree rmdir only empty. Also rmdir only empties need rm recursive force for non empty next class.

Q: mdir did not work when the directory had folders and files inside. Can we remove a directory if it is not empty? A: Not with mdir. mdir only removes empty directories. To delete a directory even if it is not empty you need the options of m, specifically the recursive and forceful form m -R and m -f. The exact command for non-empty directory removal is promised for the next class, but the principle — mdir for empty, m -R -f for everything — is established now. Keywords: rmdir did not work when directory had folders files inside can we remove non empty Not with rmdir only empties need rm recursive force for non empty next class. Also rmdir did not work when directory had folders files inside can we remove non empty Not with rmdir only empties need rm recursive force for non empty next class.

Pitfalls: Trying mdir on non-empty — fails silently by design. Using m -rf without checking pwd deletes from wrong place — catastrophic on shared server. Expect m -i prompts while m -f forces.

Recap + Bridge: Move with mv, empty-only mdir, full m -R -f, interactive m -i. Next is consolidated practice pulling all path and file operations together.

4.13 Consolidated Practice — Worksheets and Copy/Move Tasks

4.13.1 Integrated Worksheet Set

Worksheets referenced in the session pull together the path and file operations:

  • Create directories and files using both mkdir and touch or ed, then use cat with absolute paths to produce a combined file.
  • Use cp with each option -i, -p, -f, -R, -u, -n, -v to observe overwrite prompting, preservation, forced removal, recursive copy, update-only-when-newer, and no-overwrite behavior.
  • Use stat to inspect size, blocks, inode, links, permissions, UID/GID, and the three timestamps after copying.
  • Use mv -i and rm -i, rm -R, rm -f to experience the interactive prompt difference and the power of recursive deletion.
  • Use ls -l -a -i, ls -t, ls -S, ls -r, ls -R, ls -h, ls -s, and ls -s versus ls -S to internalize sorting and size reporting.

4.13.2 Execution Advice

The recurring advice is to try each command yourself exactly as shown, because parameters like /home/ubuntu/sim1 versus WI_Bangalore fail silently with no such file or directory until the path spelling matches the real tree.

Worked example — integrated worksheets: Build exact hierarchy with mkdir taking multiple arguments at once and ouch with explicit relative or absolute paths, then verify with ls -R. Tasks: cat file1 file2 > newfile.txt with absolute paths, cp -i -p -f -R -u -n -v to observe overwrite prompting preservation forced recursive update no-overwrite verbose, stat to inspect size blocks inode links permissions UID GID access modify change, mv -i and m -i rm -R rm -f for interactive versus recursive force, ls -l -a -i, ls -t, ls -S, ls -r, ls -R, ls -h, ls -s versus ls -S to internalize sorting size reporting. Verify with ls -R interleaves folder headers with contents to confirm shape. Keywords: worksheets practice captures recursive listing and copy move tasks. Also worksheets practice captures recursive listing and copy move tasks.

Execution advice: Try each command exactly as shown; parameters like /home/ubuntu/sim1 versus WI_Bangalore fail with o such file or directory until spelling matches real tree. Use ls -R snapshot to share structure without tree graphics.

Recap + Bridge: Worksheets integrate building, moving, copying, listing, and inspecting — the full daily loop. Appendices next collect exam traps and industry uses.

Exam Guidance Summary

All marks-related guidance that appeared inline is collected here:

  • Absolute path questions are trap-heavy: absolute always starts with / (root), relative never does. If a question asks for absolute, the answer must begin with /; if it asks for relative, it must be computed from the stated present working directory and must use .. correctly.
  • Common wrong paths are those that place WI_Bangalore directly under root (/WI_Bangalore) or directly under user home (~/WI_Bangalore). In the constructed hierarchy WI_Bangalore lives under sim1, so a correct absolute is /home/ubuntu/sim1/WI_Bangalore/... and a correct relative from bits is ../WI_Bangalore/....
  • Redirection symbol choice is tested: > is write or overwrite, >> is append or update. An update question expects >>. Writing a new file may use >.
  • mkdir, cd, and touch syntax expects a space between command and argument; cd.. is incorrect on Linux though it works on Windows.
  • ed overwrites without warning; there is no interactive guard like cp -i. Only permissions restrict it.
  • ls sorting: t for time newest first, S for size largest first, r for reverse, R for recursive, i for inode, a for all, l for long, h for human readable, s for allocated blocks. Do not confuse s (print size) with S (sort by size).
  • cp flags likely to be examined: i interactive before overwrite, p preserve mode ownership timestamps, f force, R recursive directories, u update only when source newer, n no overwrite, v verbose.
  • stat contents: file name, size, blocks, I/O block, file type, device ID, inode number, link count, access permissions, UID/GID, access modify change times. Modify versus change has a subtle distinction to be detailed later.
  • rmdir removes only empty directories; non-empty removal uses rm -R with optional -f for force. The full non-empty removal command beyond rmdir is deferred to the next lecture.
  • pr formats for printing: 66 lines per page, headers, pr -3 three columns, pr -j merge lines, pr -m parallel. cat displays or concatenates; pr formats; ed edits; touch creates empty.
  • Presentation advice implied: build the exact folder tree with mkdir taking multiple arguments at once and touch with explicit relative or absolute paths, then verify with ls -R.

Exam note: Absolute always starts with / (root), relative never does. From bits ../WI_Bangalore/info.txt is correct relative, /WI_Bangalore or ~/WI_Bangalore miss sim1. Update expects >> not >; mkdir cd touch need space; ed overwrites without warning; ls flags time S size reverse R recursive i inode  all l long h human readable s blocks; cp -i -p -f -R -u -n -v; stat shows size blocks inode permissions UID GID access modify change; mdir empty only, m -R -f for non-empty; pr 66 lines.

Key Industry Applications

Real-world connections that appeared with the concepts:

  • Real-world: GCC, the GNU Compiler Collection, as a canonical example of a command with dozens of options whose documentation you read offline with man gcc versus online HTML rendered from the same pages. The man system gives you internet-free reference on any Linux development machine.
  • Real-world: Hidden shell startup file .bashrc that runs at login, used in practice to auto-cd into a project directory so every terminal session starts where you work, a standard developer workflow on shared servers and personal machines.
  • Real-world: Two-way terminal chat via write and broadcast via wall paired with who to see who is available, historically used for sysadmin coordination on multi-user servers before modern chat tools.
  • Real-world: Human readable ls -h, time-sorted ls -lt, size-sorted ls -S, and recursive ls -R for daily project navigation, build artifact inspection, and log triage, complemented by inode tools ls -i and stat for file system debugging and linkage checks.
  • Real-world: touch as the modern quick way to create empty files and update timestamps in build systems, versus ed as the historical lineage of Unix editors whose a, ., w, q buffer model survives in tools like vi.
  • Real-world: Path strategy in scripts — absolute paths from root /home/ubuntu/... for stable job configurations that must work from any working directory, and relative paths with .. and . for portable repository layouts where the checkout location varies.
  • Real-world: File flow with redirection > for capturing ls -l into reports (ls -l -a -i > results.txt), concatenation with cat file1 file2 > final.doc for log merging or document assembly, and append >> for updating logs without losing history such as echo >> info.txt.
  • Real-world: Copy guards cp -i to prevent accidental overwrite in production, cp -p to preserve ownership and timestamps during backups, cp -u for incremental updates where only newer sources propagate, and cp -R for directory trees, all mirrored in release engineering pipelines.
  • Real-world: stat for forensics — checking inode numbers, block usage, ownership IDs, and access modify change times during debugging of build caches or deployment issues, with UID/GID 1000 as the typical single-user ownership marker.
  • Real-world: Printing pipeline pr with 66-line paging and column merging for legacy report formatting, still referenced in documentation for text file preparation before sending to physical printers.

Real-world tie-in: GCC man pages give offline compiler reference; .bashrc auto-cd is standard developer workflow; write/wall with who coordinated sysadmins before modern chat; ls -lah, ls -lt, ls -R, stat, ouch timestamps, redirection > >>, cp -i -p -u -R, and pr 66-line paging all map to release pipelines, build caches, and log merging in production.

SP Lecture 4 notes · Linux Commands and File System Navigation

Systems Programming· postgraduate· 2026-08-20

Sections Breakdown

1Inter-User Communication — write and wall

Two-way channel write, broadcast wall and presence discovery with who, mesg and Ctrl+D lifecycle.

2Manual Pages — man and the GCC Example

On-system manual pager man and the GCC manual as a rich example of offline documentation with Q to quit.

3Present Working Directory — pwd, Home Placement, and Hidden Startup Files

pwd as print working directory, login home placement and hidden .bashrc startup file.

4Listing Contents with ls — Meaning of . .. ~ and Every Common Option

ls long listing columns, hidden dotfiles with -a, . .. ~ / atoms and sorting flags -t -S -r -R -i -h.

5Creating Directories and Files — mkdir and touch and a Concrete Hierarchy

mkdir with multiple arguments and touch for empty files, verified by recursive ls -R in the sim1 hierarchy.

6Navigating with cd — Syntax Rules and Absolute versus Relative Paths

cd syntax spacing, variants . .. ~ / and absolute from root versus relative from present with three Goa variations.

7Guided Navigation Exercises and Reasoning

Student attempts from STD1 to ways, Pilani to ways, absolute under STD1 and mkdir ./../newdir trap counting .. steps.

8Creating and Editing Files — ed Versus touch

Quick empty touch versus classic ed buffer model a . w q and silent overwrite with permission-only guard.

9Displaying and Combining Files — cat and Printing with pr

cat display and concatenate with redirection into final.doc and pr formatting 66 lines, headers and columns.

10Redirection > and Append >> — Building, Redirecting, and Updating Files

Capturing ls -l -a -i into results.txt, concatenation with > and appending with >> and the WI_Bangalore location trap.

11Copying with cp and Statistics with stat

cp flags -i -p -f -R -u -n -v and stat fields size blocks inode permissions UID GID and three timestamps.

12Moving and Removing — mv, rmdir, and rm

mv move with -i, rmdir empty-only and rm -i -R -f recursive forceful deletion for non-empty trees.

13Consolidated Practice — Worksheets and Copy/Move Tasks

Integrated worksheet set tying mkdir touch cat cp stat mv rm and ls variants into a daily workflow loop.

14Exam Guidance Summary

Consolidated exam traps: absolute vs relative, > vs >>, spacing, ed overwrite, ls and cp flags, stat and removal.

15Key Industry Applications

Real-world maps to GCC man pages, .bashrc workflow, write/wall coordination, build pipelines, log merging and forensics.

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.

Inter-User Communication — write and wall

Must-know: Key takeaway from 4.1 Inter-User Communication — write and wall

⚠️ Top pitfall: Common pitfall in 4.1 Inter-User Communication — write and wall

Self-check: Question from 4.1 Inter-User Communication — write and wall

Connects to: None — standalone

Manual Pages — man and the GCC Example

Must-know: Key takeaway from 4.2 Manual Pages — man and the GCC Example

⚠️ Top pitfall: Common pitfall in 4.2 Manual Pages — man and the GCC Example

Self-check: Question from 4.2 Manual Pages — man and the GCC Example

Connects to: None — standalone

Present Working Directory — pwd, Home Placement, and Hidden Startup Files

Must-know: Key takeaway from 4.3 Present Working Directory — pwd, Home Placement, and Hidden Startup Files

⚠️ Top pitfall: Common pitfall in 4.3 Present Working Directory — pwd, Home Placement, and Hidden Startup Files

Self-check: Question from 4.3 Present Working Directory — pwd, Home Placement, and Hidden Startup Files

Connects to: None — standalone

Listing Contents with ls — Meaning of . .. ~ and Every Common Option

Must-know: Key takeaway from 4.4 Listing Contents with ls — Meaning of . .. ~ and Every Common Option

⚠️ Top pitfall: Common pitfall in 4.4 Listing Contents with ls — Meaning of . .. ~ and Every Common Option

Self-check: Question from 4.4 Listing Contents with ls — Meaning of . .. ~ and Every Common Option

Connects to: None — standalone

Creating Directories and Files — mkdir and touch and a Concrete Hierarchy

Must-know: Key takeaway from 4.5 Creating Directories and Files — mkdir and touch and a Concrete Hierarchy

⚠️ Top pitfall: Common pitfall in 4.5 Creating Directories and Files — mkdir and touch and a Concrete Hierarchy

Self-check: Question from 4.5 Creating Directories and Files — mkdir and touch and a Concrete Hierarchy

Connects to: None — standalone

Navigating with cd — Syntax Rules and Absolute versus Relative Paths

Must-know: Key takeaway from 4.6 Navigating with cd — Syntax Rules and Absolute versus Relative Paths

⚠️ Top pitfall: Common pitfall in 4.6 Navigating with cd — Syntax Rules and Absolute versus Relative Paths

Self-check: Question from 4.6 Navigating with cd — Syntax Rules and Absolute versus Relative Paths

Connects to: None — standalone

Guided Navigation Exercises and Reasoning

Must-know: Key takeaway from 4.7 Guided Navigation Exercises and Reasoning

⚠️ Top pitfall: Common pitfall in 4.7 Guided Navigation Exercises and Reasoning

Self-check: Question from 4.7 Guided Navigation Exercises and Reasoning

Connects to: None — standalone

Creating and Editing Files — ed Versus touch

Must-know: Key takeaway from 4.8 Creating and Editing Files — ed Versus touch

⚠️ Top pitfall: Common pitfall in 4.8 Creating and Editing Files — ed Versus touch

Self-check: Question from 4.8 Creating and Editing Files — ed Versus touch

Connects to: None — standalone

Displaying and Combining Files — cat and Printing with pr

Must-know: Key takeaway from 4.9 Displaying and Combining Files — cat and Printing with pr

⚠️ Top pitfall: Common pitfall in 4.9 Displaying and Combining Files — cat and Printing with pr

Self-check: Question from 4.9 Displaying and Combining Files — cat and Printing with pr

Connects to: None — standalone

Redirection > and Append >> — Building, Redirecting, and Updating Files

Must-know: Key takeaway from 4.10 Redirection > and Append >> — Building, Redirecting, and Updating Files

⚠️ Top pitfall: Common pitfall in 4.10 Redirection > and Append >> — Building, Redirecting, and Updating Files

Self-check: Question from 4.10 Redirection > and Append >> — Building, Redirecting, and Updating Files

Connects to: None — standalone

Copying with cp and Statistics with stat

Must-know: Key takeaway from 4.11 Copying with cp and Statistics with stat

⚠️ Top pitfall: Common pitfall in 4.11 Copying with cp and Statistics with stat

Self-check: Question from 4.11 Copying with cp and Statistics with stat

Connects to: None — standalone

Moving and Removing — mv, rmdir, and rm

Must-know: Key takeaway from 4.12 Moving and Removing — mv, rmdir, and rm

⚠️ Top pitfall: Common pitfall in 4.12 Moving and Removing — mv, rmdir, and rm

Self-check: Question from 4.12 Moving and Removing — mv, rmdir, and rm

Connects to: None — standalone

Consolidated Practice — Worksheets and Copy/Move Tasks

Must-know: Key takeaway from 4.13 Consolidated Practice — Worksheets and Copy/Move Tasks

⚠️ Top pitfall: Common pitfall in 4.13 Consolidated Practice — Worksheets and Copy/Move Tasks

Self-check: Question from 4.13 Consolidated Practice — Worksheets and Copy/Move Tasks

Connects to: None — standalone

Exam Guidance Summary

Must-know: Key takeaway from Exam Guidance Summary

⚠️ Top pitfall: Common pitfall in Exam Guidance Summary

Self-check: Question from Exam Guidance Summary

Connects to: None — standalone

Key Industry Applications

Must-know: Key takeaway from Key Industry Applications

⚠️ Top pitfall: Common pitfall in Key Industry Applications

Self-check: Question from Key Industry Applications

Connects to: None — standalone

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.