Schedule
Labs
Assignments
TA office hours
Topic videos
Some course notes
Extra problems
Lecture recordings
Repeated code is bad. If you want to do something multiple times and you copy and paste the same code, the reader has to search for any differences between the multiple seemingly-identical code blocks; and in future when you need to make changes to the code, you probably have to make the changes in all places, and you might do it differently, and it's just generally a maintenance nightmare.
Sometimes you can avoid repeating code by using a loop. But more generally, you are familiar with using "functions" or "procedures" in other programming languages so that you can "call" the same code from multiple places in your program.
We have a similar facility in sh.
First of all, though, "shell functions" aren't as nice or as useful as functions or procedures in a normal programming language. There's a standard technique of beginning a program by making a bunch of functions to do the various pieces of the program; I strongly recommend against doing that in sh. I suggest only using "shell functions" when you have some code which you need to execute from multiple places in your shell program, possibly parameterized.
Shell functions are a slightly later addition to the sh programming language, but they date from something like 1980 so all Bourne-shell-compatible shells implement them. They are safe to use in portable programs.
But you will notice immediately from the syntax that they were designed by someone other than the original shell author. The syntax is actually quite bizarre in the context of sh.
The line introducing a shell function looks like this, to create a function named "foo":
foo() {
You write the function name, no space, left parenthesis, no space, right parenthesis — even if there are parameters. And then there must also be a left brace on that line.
Then you have zero or more statements which comprise the function body; then you have a right brace on its own line to end the function.
So how do we do parameters? Well, calling the function looks like executing a command; and the command-line arguments to that command appear as $1, $2, and so on in your shell function!
A complete example appears in a separate file named "shellfunc". (Note how much more difficult it would be to write that example as a loop.)
One more note about shell functions: Don't think that you can use the "return" statement like you're used to using it in a normal programming language. "Return" in a shell function provides an exit status for the shell function. It can't be used to return a general value. (In particular, it's an eight-bit value.)
Instead, if you want a function which returns a value, have the shell function output to the standard output, and then the caller can capture this data using backquotes.