Functions
Name a block of commands.
As scripts grow, you'll repeat the same few lines in several places. A function gives those lines a name. Then you just call the name, as many times as you like.

- Scripts grow
- Repeated lines
- Give them a name
welcome.sh
A function is a name, empty brackets, and the commands inside curly braces. Greet uses dollar one, its own first argument. Line just prints a divider. Below the functions, we call them by name, like normal commands.
#!/bin/bash
greet() {
echo "Hello, $1! Welcome aboard."
}
line() {
echo "--------------------"
}
line
greet Priya
greet Alex
lineCalling functions
The divider, two greetings, and the divider again. Each function was written once, and used many times. If we change the divider, it changes everywhere.
./welcome.sh -------------------- Hello, Priya! Welcome aboard. Hello, Alex! Welcome aboard. --------------------
Function tips
Define functions before you use them, usually at the top of the script. Give them names that say what they do, like make backup, or check disk. Use local for variables that belong only inside the function. And return a number, to report success or failure.
| key | value |
|---|---|
| name() { … } | define it |
| name arg1 arg2 | call it |
| $1 inside | the function's argument |
| local x=1 | a private variable |
Summary
Functions name a block of commands, so you can reuse it. Define them at the top, and call them by name, with arguments. Next, making scripts stop safely when something fails.
Key takeaways- name() { … }
- name arg
- local