Function Basics
A function is like a recipe card you write once and use again and again. You give it a name, and every time you say that name the computer follows the steps.
In this page:
Syntax
function_name() {
commands
}
function_name
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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Writing
greet() { ... }and then calling it asgreet(), when it is called with justgreet. - Calling a function before its definition.
- Redefining a function with the same name as an existing command, which hides that command in the script.
🔒
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