|
Functions let you group commands together and reuse them throughout your script. They’re essential for organizing larger scripts. Define a function using the |
|
|
Bash
Bash supports an alternative syntax using the
|
|
|
Bash
You can also combine both syntaxes: |
|
|
Bash
Call a function by using its name. |
|
|
Output:
Hello, World! |
|
|
Functions can accept arguments via |
|
|
Output:
Hello, Alice! Hello, Bob! |
|
|
|
|
|
Output:
Number of arguments: 3 - one - two - three |
|
|
Functions return exit status with |
|
|
Output:
4 is even 7 is odd |
|
|
To return string values, use command substitution. |
|
|
Output:
Got: Hello, World! |
|
|
Variables in functions are global by default. Be careful with naming to avoid conflicts. |
|
|
Output:
Counter: 2 |
|
|
Bash
Bash provides the |
|
|
Output:
Sum: 15 Result: global |
|
|
Functions must be defined before they’re called. Unlike some languages, shell scripts are interpreted top-to-bottom, so calling an undefined function fails. |
|
|
Output:
/script: line 7: undefined_func: not found Hello, World! |
|