Function Arguments
Function arguments are like the ingredients you hand to a recipe. Inside the function you refer to the first, second and third thing you were given by number.
In this page:
Syntax
function_name() {
echo "$1" "$2" # arguments
echo "$#" # argument count
}
function_name arg1 arg2
Function Arguments
Functions receive arguments the same way scripts do: $1, $2, etc. for individual arguments, $# for the count, and $@ for all of them.
There's no separate parameter-declaration syntax like in other languages — arguments are simply read positionally inside the function body. Function-local $1 shadows the script's own $1 while the function is running.
Note:
Inside a function,
$1 refers to the function's own first argument, not the script's.Example: Function Arguments
#!/bin/bash
greet() {
echo "Hello, $1! You are $2 years old."
}
greet "Alice" 30
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
- Using
$1and expecting names, when arguments are positional. - Forgetting quotes around
"$@", so arguments with spaces are split. - Expecting
$0inside a function to be the function name.
🔒
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