How to Call a Function in Bash: Simple Syntax and Example
In Bash, you call a function simply by writing its name followed by parentheses like
function_name() or just function_name. The function must be defined before you call it in the script.Syntax
To call a function in Bash, you just write its name followed by parentheses (). You can also call it without parentheses. The function must be defined earlier in the script.
Example parts:
function_name(): defines the functionfunction_name: calls the function(): parentheses are optional when calling
bash
function_name() {
echo "Hello from function"
}
function_name # calling the functionOutput
Hello from function
Example
This example shows how to define a function named greet and call it to print a message.
bash
# Define the function greet() { echo "Hello, welcome to Bash functions!" } # Call the function greet
Output
Hello, welcome to Bash functions!
Common Pitfalls
Common mistakes include calling a function before it is defined, forgetting parentheses in the definition, or using incorrect syntax.
Also, calling a function with parentheses is optional, but parentheses are required in the definition.
bash
# Wrong: calling before definition
# greet
# greet() {
# echo "Hi"
# }
# Right: define first, then call
greet() {
echo "Hi"
}
greetOutput
Hi
Quick Reference
| Action | Syntax | Notes |
|---|---|---|
| Define function | function_name() { commands; } | Parentheses required in definition |
| Call function | function_name or function_name() | Parentheses optional when calling |
| Call before define | Not allowed | Function must be defined before calling |
| Pass arguments | function_name arg1 arg2 | Access with $1, $2 inside function |
Key Takeaways
Define your Bash function before calling it in the script.
Call functions by their name with or without parentheses.
Parentheses are required only in the function definition, not in the call.
Passing arguments to functions is done by listing them after the function name.
Avoid calling functions before they are defined to prevent errors.