IFI 8410 — Session 6: Unix File System and Command Line

The Blueprint of Modern Computing

One tree, small tools, and text flowing between them

Where we are going

Today in four moves

1Where it came from

Ideas, not just an OS

Multics → UNIX → BSD, Linux, macOS. Why a 1970s design still runs the cloud.

2The tree and the shell

Knowing where you are

One root, paths, the working directory, and the commands that move and organize.

3Streams and pipes

Composition

stdin, stdout, stderr; redirection with >; pipelines with |.

4Your own tools

From typing to scripting

Permissions, executable scripts, and running Python from the shell.

Running example: what are the most frequent words in Shakespeare? — answered without writing a program.

Which one am I on?

The family is real, and you are in it

$ uname -s
Darwin # macOS — a certified UNIX, BSD lineage
Linux # the ARC cluster, most servers, WSL

$ echo $SHELL
/bin/zsh # default on macOS
/bin/bash # default on most Linux systems
  • The commands in this session work the same in bash and zsh.
  • Small differences exist between GNU (Linux) and BSD (macOS) versions of tools — check man command on your own machine.
  • Windows: use WSL, or work on the course server over SSH.

Do one thing well

Each tool is almost insultingly simple

wc -l   # count lines
sort    # put lines in order
uniq -c # collapse repeats, with a count
grep    # keep lines that match
head    # show the first few
tr      # translate or delete characters
  • None of them knows anything about your data.
  • None of them opens a window, asks a question, or holds state.
  • Each reads text in and writes text out — which is exactly why they can be combined.

The power is not in any one tool. It is in the interface they share.

Reading a command line

Command, options, arguments

ls
the program
-la
options / flags
projects
argument
$ ls -la projects
total 24
drwxr-xr-x 5 student staff 160 Sep 30 09:12 .
drwxr-xr-x 12 student staff 384 Sep 30 09:10 ..
-rw-r--r-- 1 student staff 1044 Sep 30 09:12 notes.txt

The shell reads the line, expands shorthand such as ~ and *, then starts the program. The program never sees the wildcard — only the filenames it matched.

Why bother

When the shell is the right tool

Remote work

Over SSH there is often no desktop at all — the cluster, the server, the container.

Repetition

The same operation on 10,000 files, run again next month with one command.

Composition

Ad-hoc questions answered by connecting tools no one wrote for that question.

Reproducibility

A recorded command is evidence; a sequence of mouse clicks is a memory.

The terminal is not an alternative to programming — it is one of the environments programming happens in.

Knowing where you are

Three commands, most of the time

$ pwd # print working directory
/home/student/ifi8410

$ ls data # what is in there?
scores.csv shakespeare.txt

$ cd data # go somewhere else
$ cd .. # back up one level
$ cd ~ # home
$ cd - # back where I just was

Absolute — from the root, means the same anywhere:
/home/student/ifi8410/data/scores.csv

Relative — from where you stand right now:
data/scores.csv

Building a workspace

Create, copy, move, remove

$ mkdir -p project/data project/out # -p: make parents, don't complain
$ cp notes.txt project/ # copy (-r for directories)
$ mv notes.txt project/README.txt # move — and rename
$ rm project/out/draft.txt # remove. permanently.
  • Separate inputs from outputs: you can delete out/ and rebuild it without risking data.
  • cp and mv overwrite the target without asking.
rm has no undo and no trash can. Before rm -r with a wildcard, run ls on the same pattern and read what it matched. Check pwd first.

Looking without opening

A 5 MB file is not for your editor

$ wc -l data/shakespeare.txt
196024 data/shakespeare.txt

$ head -n 3 data/pg100.txt # first lines; tail for the last
The Project Gutenberg eBook of The Complete Works of William Shakespeare
 
This eBook is for the use of anyone anywhere in the United States and
# ...so the file is not all Shakespeare

$ grep -c -i -w "love" data/shakespeare.txt # lines containing the word
2342

less file pages through interactively — space scrolls, / searches, q quits. It never loads the whole file into memory, so it opens a gigabyte instantly.

Reading the nine characters

Permissions in practice

$ ls -l wordfreq.sh
-rw-r--r-- 1 student staff 219 Sep 30 11:02 wordfreq.sh
^^^ ^^^ ^^^ owner / group / others — r read, w write, x execute

$ chmod +x wordfreq.sh # add execute permission
$ ls -l wordfreq.sh
-rwxr-xr-x 1 student staff 219 Sep 30 11:02 wordfreq.sh

$ ./wordfreq.sh # ./ = "the file here", not on $PATH
  • On a directory, x means "may enter" — without it you cannot cd in, even if you can read it.
  • chmod 755 is the same as rwxr-xr-x — one digit per class.

Why two output channels

Results and complaints travel separately

import sys

# the answer — the next program's input
print(f"{count} {word}")

# the commentary — for a human
print("warning: 3 rows skipped",
      file=sys.stderr)
  • If warnings went to stdout, they would land in your data file.
  • Mixing them is the single most common way to corrupt a pipeline.
  • Rule of thumb: anything a human reads goes to stderr; anything a program reads goes to stdout.

Same rule in the shell: echo results, but send progress messages with echo "..." >&2.

Repointing the channels

Redirection, four symbols

$ python3 summarize.py data.csv > summary.txt # stdout to a file (replaces)
$ echo "run 2" >> log.txt # append instead of replace
$ sort < names.txt # stdin from a file
$ python3 summarize.py data.csv 2> problems.txt # stderr to its own file

$ ls data/real.txt data/missing.txt > found.txt 2> errors.txt
$ cat errors.txt
ls: data/missing.txt: No such file or directory

2>&1 merges stderr into stdout — one combined stream.

2>/dev/null discards errors entirely. Use it deliberately, not by habit.

Building it one stage at a time

Most frequent words in Shakespeare

tr -d '.,:;?!"()[]' < data/shakespeare.txt \
| tr 'A-Z' 'a-z' \
| tr -s ' \t\r' '\n' \
| grep -v -e '^[[:space:]]*$' \
| sort \
| uniq -c \
| sort -rn \
| head -n 5
30249 the
28388 and
21672 i
20598 to
18736 of
  • Six tools, no program, no temporary files.
  • Each stage is inspectable on its own — pipe into head and look.
  • The answer is function words — which is itself the finding.

From typing to tooling

A pipeline you repeat is a script

#!/bin/bash
# Read text on stdin,
# write "count word" on stdout.
tr -d '.,:;?!"()[]' \
| tr 'A-Z' 'a-z' \
| tr -s ' \t\r' '\n' \
| grep -v -e '^[[:space:]]*$' \
| sort | uniq -c | sort -rn
  • Hash-bang #!/bin/bash on line 1 names the interpreter.
  • chmod +x wordfreq.sh makes it runnable.
  • No filenames inside — it reads stdin, so it composes like a built-in tool.
$ sed -n '/HAMLET/,/KING HENRY/p' data/shakespeare.txt | ./wordfreq.sh | head -3
1112 the
980 and
725 to

The shell starts your programs too

Running Python from the command line

import sys
from pathlib import Path

def main():
    if len(sys.argv) < 2:
        print("usage: wordfreq.py FILE [N]",
              file=sys.stderr)
        return 1                  # exit status
    path = Path(sys.argv[1])
    top_n = int(sys.argv[2]) if len(sys.argv) > 2 else 20
    ...

if __name__ == "__main__":
    sys.exit(main())
$ python3 wordfreq.py shakespeare.txt 5
30249 the
28388 and

$ python3 wordfreq.py
usage: wordfreq.py FILE [N]
$ echo $?
1 # 0 = success
  • sys.argv carries the words after the command.
  • The exit status is how scripts test whether a step worked.

Same operating system, two dialects

The shell command and its Python twin

ShellPython
pwdPath.cwd()
lsPath(".").iterdir() · Path(".").glob("*.csv")
mkdir -p out/reportsPath("out/reports").mkdir(parents=True, exist_ok=True)
cp · mv · rmshutil.copy() · shutil.move() · Path.unlink()
~Path.home()
cmd > file · cmd 2> filesys.stdout · sys.stderr

Neither is "the real way". The shell is for interactive work and quick composition; Python is for logic that belongs in a program.

Now: hands-on

Open a terminal

1Notebook

Guided

06-Unix-Command-Line — the word-frequency pipeline, built stage by stage, with a Your turn section at the end.

2Read

Reference

File System and CLI for the commands, UNIX Overview for the ideas, UNIX Reference to go further.

Homework 5 — organize a directory tree from the shell, run your scripts from the command line, and show the commands you used. Due Wednesday, October 14.

Take away

Nine things worth remembering

  • The file system is one tree rooted at /; your working directory decides how relative paths resolve.
  • pwd, ls, cd answer where you are, what is here, how to move — check before you act.
  • mkdir, cp, mv, rm organize the tree; rm has no undo.
  • Every program has three streams: stdin, stdout, stderr.
  • Results on stdout, messages on stderr — that separation is what makes composition safe.
  • > and >> send output to a file; < feeds input from one; | connects one program to the next.
  • A repeated pipeline belongs in a script: hash-bang plus chmod +x.
  • Permissions answer who may do what: read, write, execute for owner, group, others.
  • sys.argv, exit status, and pathlib are the same ideas, seen from inside Python.
◀ Slides