Send a program’s output into another program, or into a file
Feed one tool’s output to another as a list of files to work on
Chain commands so the next one runs only if the last one worked
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 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.
See what the glob expands to first:
echo *.txt
The shell replaces *.txt with the matching names before echo runs.
Now print the contents of all of them:
cat *.txt
John leaves a TODO behind wherever he gave up.
Find them in his code, and only his code:
grep TODO *.c
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.
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.
Run it:
./prog
Nothing happens.
It is waiting for stdin.
Type 3 and press Enter.
Now give it the number up front:
./prog 3
It waits again.
Why didn’t prog use the 3?
Solution
prog only reads stdin.
A number typed after the command is not stdin, so prog ignores it.
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.
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.
Count them by hand.
Copy the names, run wc -l, paste, press Enter, then press Ctrl-D:
wc -l
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.
Print the whole passage, all 10 lines:
echo 10 | ./prog
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.
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:
Write to the file:
echo "Hello World" > output.txtcat output.txt
Write to it again with >:
echo "Hello Again" > output.txtcat output.txt
Now with >>:
echo "Hello Again" >> output.txtcat output.txt
What’s the difference between > and >>?
Solution
> overwrites the file each time; >> appends to the end.
After step 2 the file has one line; after step 3 it has two.
Create a file count.txt with the following content:
5
Give it to prog through <:
./prog < count.txt
What about <<? (extra)
Acksually, << isn’t the input version of >>.
It doesn’t read a file at all.
It feeds the lines you type, up to a marker, into stdin:
sort << EOFpearapplemangoEOF
This is called a here document.
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.
Run this, and count what you see:
ls *.txt | wc -l
wc -l read the list itself, so you got the number of files.
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:
xargs turned 3 into an argument,
and prog ignores its arguments.
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.
Run ls first. prog is still there from the earlier exercise
Combine the two commands into one line:
clang main.c -o prog && echo 3 | ./prog
If compilation succeeds, prog is rebuilt and then runs.
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.
Fix the semicolon and run it once more
How does | differ from &&?
Solution
| passes the left program’s output into the right program. && passes nothing; it only checks whether the left program succeeded.
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.
Open a new file:
vim build.sh
Put these two lines in it, then save and quit:
#!/bin/shclang 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.
A file needs execute permission before it can run. Add it:
chmod +x build.sh
Run it:
./build.sh
Change a line of main.c, then run ./build.sh again
instead of retyping anything.
Reading the permission bits (extra)
Every file carries a set of permissions saying who is allowed to do what with it.
You’ve been looking at them this whole time without reading them:
ls -l main.c
-rw-r--r-- 1 abc abc 787 Oct 8 09:24 main.c
Ignore the leading - and read the rest in three groups of three:
Group
Who it applies to
rw-
you, the owner
r--
others in your group
r--
everyone else
Within each group, the three slots are always in the same order:
r: read; you can look at the contents
w: write; you can change it
x: execute; you can run it
So rw-r--r-- reads as: the owner can read and write,
everyone else can only read,
and nobody can execute it.
After chmod +x it becomes -rwxr-xr-x.
You’ll also see permissions written as numbers, like chmod 755.
It’s the same thing in a shorter notation.
And what does it even mean to “execute” a directory?
Think of it as permission to enter the folder: to cd into it, or double-click it open.
We’ll leave the details to an OS course, but feel free to experiment.
Command History and Shortcuts (Extra)
You can recall earlier commands and edit them at the prompt.
Try the shortcuts below.
Keybinding
Action
Up / Down
Step through previous commands
Ctrl-R
Search 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.
Keybinding
Action
Ctrl-L
Clear screen
Ctrl-A
Move to beginning of line
Ctrl-E
Move to end of line
Meta-Backspace
Kill word
Ctrl-U
Kill from cursor to beginning of line
Ctrl-K
Kill 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.
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:
Extract the archive
Locate the .c files that contain a TODO, and only those
Delete every line containing [debug] (in any case) from those files
Run verify . inside robert to check your work and record your completion:
abc@tut7:~/tutorial-graded/robert$ verify .
Solution
tar xf robert.tar.gzgrep -ril --include='*.c' todo robert/ \ | xargs sed -i '/\[debug\]/Id' # only .c files with a TODOverify robert/
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.