Bash Functions
A function is a named block of commands in a script. Calling the name runs the commands inside the block.
Define and call a function
The greet function holds one echo command. Calling greet by name runs that command.
greet() {
echo "Hello from the greet function"
}
greetCall a function twice
The same function is called on two lines. Its message is printed two times.
say_ready() {
echo "Ready to go"
}
say_ready
say_readyDefine before you call
This script calls greet before Bash has read its definition. Bash reports that the greet command is not found.
greet
greet() {
echo "Hello from the greet function"
}Example
greet() {
echo "Welcome to the backup tool"
}
show_steps() {
echo "Step 1: choose a folder"
echo "Step 2: copy the files"
}
greet
show_steps
echo "Tool ready"Key points
- A function definition starts with the name followed by parentheses.
- The commands of a function sit between curly braces.
- Calling a function means writing its name on a line by itself.
- A function must be defined before it is called.
- One function can be called many times in a script.
- Functions keep a repeated job in one place.
In this example, two functions are defined at the top of the script. Each function is called once by name below its definition. The final echo runs after both calls finish.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What happens when a script calls a function before its definition?