How to Create a Function in Bash: Syntax and Examples
In Bash, you create a function using the syntax
function_name() { commands; } or function function_name { commands; }. Call the function by typing its name in the script or terminal.Syntax
A Bash function is defined by its name followed by parentheses and a block of commands inside curly braces. You can use either function_name() { ... } or function function_name { ... }. The commands inside run when you call the function by its name.
- function_name: The name you choose for your function.
- (): Parentheses after the name (required in the first style).
- { ... }: Curly braces contain the commands to run.
bash
my_function() {
echo "Hello from my_function"
}
# Or alternatively
function my_function {
echo "Hello from my_function"
}Example
This example shows how to define a function that prints a greeting and then call it. It demonstrates the basic function creation and usage in Bash.
bash
greet() {
echo "Hello, $1!"
}
greet "Alice"Output
Hello, Alice!
Common Pitfalls
Common mistakes include forgetting the parentheses () in the function definition, missing spaces around braces, or not calling the function after defining it. Also, avoid putting spaces between the function name and parentheses.
bash
# Wrong: missing parentheses
myfunc {
echo "This will cause an error"
}
# Correct:
myfunc() {
echo "This works fine"
}
# Note: space between name and parentheses is allowed in Bash
myfunc () {
echo "This also works, but avoid space for consistency"
}Quick Reference
| Concept | Syntax | Description |
|---|---|---|
| Define function | name() { commands; } | Create a function named 'name' |
| Call function | name | Run the function by its name |
| Pass argument | name arg1 | Send 'arg1' to function as $1 |
| Access argument | $1, $2, ... | Use inside function to get passed arguments |
| Return value | return value | Exit function with a status code |
Key Takeaways
Define a Bash function using 'name() { commands; }' or 'function name { commands; }'.
Call the function by typing its name followed by any arguments.
Always include parentheses '()' after the function name in definitions.
Use '$1', '$2', etc., inside functions to access passed arguments.
Avoid spaces between the function name and parentheses for clarity.