CHAPTER 11 · 7 lessons · 91 exercises
Write a script
Put the steps you typed into a file, so you can call them by name.
If you type the same three lines every time, that is a program already.
Write the steps in a file, put #! on the first line, and add the mark that says it may run. Then ./setup.sh is all it takes.
#!and the execute permission — how to make a file that runs- variables and arguments —
$1$2$@ ifandtest— is the file there, are the values the samefor— take a row of things in turnwhile— repeat while a condition holds- exit status —
$?and&&|| - functions — give a name to a lump of it
If you came through the JavaScript or Python course, you already know branching and repetition; all you learn here is how they are written. And if this is your first programming, this is the chapter where you see that a program is just those three: run in order, branch on a test, repeat.
Exit status is a way of thinking peculiar to the shell, so take that part gently. There is a back-to-front rule that success is 0 and failure is anything else, and it is what lets you join things with && (if the one before succeeded, then the next).
By the end of this chapter, the command line turns from "somewhere you type" into somewhere you keep your tools.
Lessons in this chapter
Scripts and the execute permission
- 58`#!` and the execute markWrite the steps you typed into a file, so you can call them by a name of your own.Go to the exercises
- 59Taking arguments (`$1`)Make the words written after your script usable inside it.Go to the exercises
Branching, loops, exit status
- 60Branching with `if`Look at a condition and change what you do. See that
[is a command and it all joins up.Go to the exercises - 61Repeating with `for`Take things off a row one at a time and do the same to each.Go to the exercises
- 62`while` and `read`Go round while a condition holds. Read lines one at a time, without splitting them.Go to the exercises
- 63Exit statusEvery command hands back a success or failure. Read it, and put one on your own tools.Go to the exercises
- 64Giving names with functionsGive a lump of procedure a name and call it as often as you like. The close of chapter 11.Go to the exercises