Coding for All
Lesson 7: Functions
Functions Give a piece of your script a name and reuse it.
1#!/bin/bash
2greet() {
3 echo "Hello, $1!"
4}
5
6greet "Ada"
7greet "Sam"
Terminal
$ ./greet.sh
Hello, Ada!
Hello, Sam!
Every line, explained
#!/bin/bash
This first line is called the shebang (from "hash bang", the # and ! it starts with). It is not a comment: it tells the computer which program should read the rest of the file. #!/bin/bash means "run this with bash". Every bash script starts with this exact line.
greet() {
This defines a function: a chunk of the script with a name, so you can run it whenever you like. The empty round brackets say "this is a function", and the body goes between the curly brackets. Defining a function does not run it: the lines inside just wait, quietly, until somebody calls the name.
echo "Hello, $1!"
Inside a function, $1 means the first thing given to the FUNCTION (not to the script). So this line greets whoever is handed over.
}
The closing curly bracket ends the function. Everything between the brackets belongs to greet.
greet "Ada"
Writing a function's name runs it, exactly like running a command. Anything you write after the name arrives inside as $1, just like a script's arguments.
greet "Sam"
Writing a function's name runs it, exactly like running a command. Anything you write after the name arrives inside as $1, just like a script's arguments. Written once, used twice: that is the entire point of a function.