Tutorial Goals

By the end you’ll be able to:

  1. Run one command against many files at once
  2. Send a program’s output into another program, or into a file
  3. Feed one tool’s output to another as a list of files to work on
  4. Chain commands so the next one runs only if the last one worked
  5. Save a sequence of commands as a script, and make it runnable

Motivation

John has spelled his own name wrong all over his files,
writing “John Dough” instead of “John Doe”.
He wants to know how bad it is, then fix it.
Even though he attended
the previous tutorial,
he would still have to go through them one file at a time.

John’s TA did it with two lines:

grep "John Dough" *.c | wc -l
sed -i 's/John Dough/John Doe/g' *.c

John was so impressed that he wanted to learn how it works.
By the end of this tutorial, so will you.

Wildcard Expansion (Globbing)

File globbing (wildcard expansion) is how you match many files at once.

The shell processes the glob before handing it to the program.
If there’s a file1.txt and file2.txt in the current directory and you type echo *.txt, the shell replaces *.txt with every matching file first.
echo never sees *.txt; it sees file1.txt file2.txt.

A glob works anywhere a list of files is expected,
so any tool from this tutorial will work with globs.

  1. See what the glob expands to first:

    echo *.txt

    The shell replaces *.txt with the matching names before echo runs.

  2. Now print the contents of all of them:

    cat *.txt
  3. John leaves a TODO behind wherever he gave up.
    Find them in his code, and only his code:

    grep TODO *.c
  4. Now widen the glob to every file:

    grep TODO *

    You get more hits, but the extra ones are from notes.txt.
    Those are not code. Narrowing the glob to *.c is what kept them out.

(Extra) One file is literally named *.txt, because he got the quoting wrong.
Quote it so the shell does not expand it:

cat '*.txt'

Tip

If you know regular expressions: globbing may look like them, but they are not the same thing.

Try out the patterns here:
https://www.digitalocean.com/community/tools/glob

Pipelines

Where does input and output go?

Every program takes some input and produces some output.
It reads its input from stdin (standard input),
and writes its output to stdout (standard output).

In most cases, stdin is your keyboard and stdout is your screen.
But these are just defaults.

prog prints the first few lines of a passage from the Bee Movie.
You choose how many.

  1. Run it:

    ./prog

    Nothing happens.
    It is waiting for stdin.
    Type 3 and press Enter.

  2. Now give it the number up front:

    ./prog 3

    It waits again.

Why didn’t prog use the 3?

What follows is about re-wiring them:
to another program, or to a file.

Connecting multiple tools (|)

Each tool does one small job. Real problems need several, so you have to combine them.

A pipe (|) connects one program’s standard output to the next program’s standard input.

dupes.txt contains a list of text editors and a list of SI prefixes.
Find the names that appear in both.

  1. uniq -d prints only lines that repeat, but it only sees repeats that are
    next to each other. So sort first:

    sort dupes.txt | uniq -d

    Those are the names on both lists.

  2. Count them by hand.
    Copy the names, run wc -l, paste, press Enter, then press Ctrl-D:

    wc -l
  3. Now count them without copying anything:

    sort dupes.txt | uniq -d | wc -l

A pipe does the copy and paste for you.
Whatever uniq -d prints goes into wc -l as if you had pasted it yourself.

John wrote prog, and the passage it prints should match expected.txt.
Compare them using diff.

  1. Print the whole passage, all 10 lines:

    echo 10 | ./prog
  2. Pipe it into diff.
    A - where diff expects a filename means “read stdin instead”:

    echo 10 | ./prog | diff - expected.txt

    diff prints only the lines that differ. One word is wrong.

  3. Read both yourself with cat and ask whether you would have spotted it

Redirection

A pipe connects a program to another program.
Redirection connects it to a file instead.
> and >> send stdout into a file, and < reads stdin from one.

Run these in order:

  1. Write to the file:

    echo "Hello World" > output.txt
    cat output.txt
  2. Write to it again with >:

    echo "Hello Again" > output.txt
    cat output.txt
  3. Now with >>:

    echo "Hello Again" >> output.txt
    cat output.txt

What’s the difference between > and >>?

  1. Create a file count.txt with the following content:

    5
  2. Give it to prog through <:

    ./prog < count.txt

Passing a list along (xargs)

A pipe pastes text into the next program’s stdin.
But rm never reads stdin, so there is nowhere to paste.
It only looks at the filenames you type after it, its arguments.

xargs takes what comes down the pipe and types it in as arguments for you.

  1. Run this, and count what you see:

    ls *.txt | wc -l

    wc -l read the list itself, so you got the number of files.

  2. Count the lines inside each file by hand.
    Run ls *.txt and copy the names it prints.
    Then type wc -l , paste the names after it, and press Enter.
    For instance:

    wc -l count.txt dupes.txt expected.txt notes.txt '*.txt'
  3. Now let xargs do the typing:

    ls *.txt | xargs wc -l

    You get the same result as step 2.

  4. Try the same with prog:

    echo 3 | xargs ./prog

    Nothing is printed.

Why did echo 3 | xargs ./prog print nothing?

Chaining commands

Sometimes you want to run one command based on whether another worked.

&& wants both commands to succeed.
If the first one fails, there’s no point running the second, so it doesn’t.
|| only needs one of them to succeed.
If the first one succeeds, the second never runs.

Every time John changes main.c he compiles it, then runs it. Two commands, every time.

  1. Run ls first. prog is still there from the earlier exercise

  2. Combine the two commands into one line:

    clang main.c -o prog && echo 3 | ./prog

    If compilation succeeds, prog is rebuilt and then runs.

  3. Now break the code on purpose (delete a semicolon in main.c) and run the same line again
    The compile fails, so ./prog never runs, and you don’t accidentally run the old binary.

  4. Fix the semicolon and run it once more

How does | differ from &&?

Saving your commands

To write a shell script, put the commands you would normally run in the terminal into a text file.
Save the compile-and-run command in build.sh.

  1. Open a new file:

    vim build.sh
  2. Put these two lines in it, then save and quit:

    #!/bin/sh
    clang main.c -o prog && echo 3 | ./prog

    The first line is called the shebang (#!, read “hash-bang”).
    It tells the system which program runs the rest of the file,
    here /bin/sh, a shell.

  3. A file needs execute permission before it can run. Add it:

    chmod +x build.sh
  4. Run it:

    ./build.sh
  5. Change a line of main.c, then run ./build.sh again
    instead of retyping anything.

Command History and Shortcuts (Extra)

You can recall earlier commands and edit them at the prompt.
Try the shortcuts below.

KeybindingAction
Up / DownStep through previous commands
Ctrl-RSearch your history
!!The entire last command

Ctrl-R is the big one. Press it, type a few letters of a command you ran earlier, and the shell finds it.
Press Ctrl-R again to go further back.

!! stands in for your last command.
The classic use: you run a command, it fails with “Permission denied” because you forgot sudo.
Instead of retyping the whole thing, just prepend it:

sudo !!

which reruns your last command with sudo in front.

Note

Read sudo !! aloud as “sudo bang bang”, since ! is called “bang”.

Editing at the prompt (readline)

Just like Vim, the terminal lets you edit the line you’re typing.
This is powered by a library called readline.

KeybindingAction
Ctrl-LClear screen
Ctrl-AMove to beginning of line
Ctrl-EMove to end of line
Meta-BackspaceKill word
Ctrl-UKill from cursor to beginning of line
Ctrl-KKill from cursor to end of line

Note

Meta is usually the Alt key. On a Mac, it might be the Option key.

And there’s plenty more. Alt-. even pulls in the last argument of your previous command:
after mkdir project, just type cd, press Alt-., and you get cd project for free.

To see how far readline really goes, watch https://www.youtube.com/watch?v=MxRTh8wlmJk.

When the line gets too long

When the line is long enough that none of the keybindings help, press Ctrl-X Ctrl-E.

The whole command opens in your editor.
Fix it there with everything you learned in the vim tutorial,
save, quit, and the shell runs what you saved.

Tip

It opens Vim by default.
If you’d rather have nano, set $EDITOR:

export EDITOR=nano

Graded Task(s)

If you recall previously,
Bob asked you for help.
After you flamed him for his fake .tar.gz,
he now knows how to archive files and name them properly.
Turns out, he realises that there were more than one such files.
He needs to remove the [debug] lines from every .c file that has a “TODO” comment.
Would you help him? (I don’t think you have much of a choice)

Enter the Graded Task Folder

Go to ~/tutorial-graded before starting

Help Bob make the following changes:

  1. Extract the archive

  2. Locate the .c files that contain a TODO, and only those

  3. Delete every line containing [debug] (in any case) from those files

  4. Run verify . inside robert to check your work and record your completion:

    abc@tut7:~/tutorial-graded/robert$ verify .
    

Info

The verify program runs on the entire directory,
because Bob wants to make sure that you didn’t mess up the other files.

Before you leave: verify your progress

Run this command inside your Tutorial environment:

progress

It shows whether you have successfully completed the tutorial and which
individual tasks have been recorded as complete.

The progress command is available only inside a Tutorial environment, not in
the general CS1010 WebTop environment.