Function Basics
In this page:
Function Basics
A Bash function groups commands under a name using function_name() { ... }, letting you call the same logic repeatedly without duplicating code. Functions must be defined before they are called in the script. They're invoked just like any other command, by writing their name.
Note: The function keyword before the name is optional in Bash — greet() { ... } and function greet { ... } both work.
Example: Function Basics
#!/bin/bash
greet() {
echo "Hello from a function!"
}
greet
greet
Login to try C/C++/Java/PHP code in the editor
🔒
Chapter Quiz — Complete all 13 topics to unlock
0/13 topics done
Complete these topics first:
- Function Basics
- The read Command and Here-Strings
- Function Arguments
- stdin, stdout, stderr and File Descriptors
- Return Values
- Redirection Operators
- Local Variables
- Pipes and Chaining Commands
- Recursive Functions
- Here-Documents (<<EOF)
- Function Libraries
- The tee Command
- Discarding Output with /dev/null