One of the great things about Unix is that it's made up of individual utilities, "building blocks" like cat and grep, that you run from a shell prompt. Using pipes, redirection, filters, and so on, you can combine those utilities to do an incredible number of things. Shell programming lets you take the same commands you'd type at a shell prompt and put them into a file you can run by just typing its name. You can make new programs that combine Unix programs (and other shell scripts) in your own way to do exactly what you need. If you don't like the way a program works, you can write a shell script to do just what you want.
Because many Unix users use the shell every day, they don't need to learn a whole new language for programming, just some tips and techniques. In fact, this chapter covers a lot of programming techniques that you'll want to use even when you aren't programming. For example, loops and tests are handy on the command line.
(This series of articles does assume that you've written programs in some language before or are generally familiar with programming concepts. If you haven't and aren't, you might start with a more comprehensive shell programming book.)
This chapter discusses only Bourne shell programming. We don't cover many features from more advanced Bourne-type shells, like bash and zsh, because those can make your shell scripts nonportable; we stick to concepts that should work almost anywhere. Also, in most cases, the C shell isn't great for shell programming.
A
note about command versions: unfortunately, the same commands on different
versions of Unix can have different options. Some Bourne shells are a little
different from others. For instance, some test
(Section 35.26) commands have a
-x
option to test for an executable file; others don't.
Some echo commands use a -n
option to mean "no newline at the end of this string"; others have you put
\c
at the end of the string. And so on.
Where there are differences, these articles generally use the commands in
original Berkeley Unix from the 1980s. If a command doesn't seem to work on your
system, check its online manual page or the sh manual page.
— JP