Passing Arguments to Functions
A function becomes much more useful when it can work on different data each time it is called. In Bash you pass data to a function the same way you pass it to a command: you write the values after the function name, separated by spaces. Inside the function, those values are available as positional parameters: $1, $2, $3 and so on.
There is no parameter list in the definition. The parentheses in name() { ... } always stay empty. The function decides inside its body how many arguments it expects and what they mean.
Basic Example
greet() {
echo "Hello, $1! You are number $2."
}
greet Ana 7
Output:
Hello, Ana! You are number 7.
The call greet Ana 7 gives the function two arguments. Inside the body, $1 is Ana and $2 is 7. The command-line parameters from lesson 42 work in exactly the same way, with the function's arguments in place of the script's arguments.
The Special Parameters in a Function
All the special parameters of lesson 43 are available inside a function:
| Parameter | Meaning inside a function |
|---|---|
$1, $2, ... | The first, second, ... argument |
${10} | The tenth argument (braces are required from 10 on) |
$# | The number of arguments |
$@ | All arguments, as separate words |
$* | All arguments, as one word when quoted |
$0 | The name of the script, not of the function |
show() {
echo "count: $#"
echo "first: $1"
echo "all: $*"
}
show red green blue
show
count: 3
first: red
all: red green blue
count: 0
first:
all:
When the function is called without arguments, $# is 0, and $1 and $* are empty strings. Bash does not report an error for a missing argument unless you ask for one (see below). The name of the function itself is not in $0: Bash leaves $0 as the script name, and the function name is available as ${FUNCNAME[0]} (lesson 88).
The tenth argument needs braces, because $10 is read as $1 followed by the character 0:
tenth() { echo "10th with braces: ${10}; without: $10"; }
tenth 1 2 3 4 5 6 7 8 9 ten
10th with braces: ten; without: 10
Quoting Arguments with Spaces
The shell splits a command line into words before the function runs. The function receives the words, not the original line. To pass a value that contains spaces as one argument, quote it (lessons 46 and 55):
count_args() { echo "$# arguments"; }
count_args one two three
count_args "one two" three
count_args "one two three"
name="Ana Maria"
count_args $name
count_args "$name"
3 arguments
2 arguments
1 arguments
2 arguments
1 arguments
The unquoted $name was split into two words by word splitting (lesson 53), so the function saw two arguments. The quoted "$name" stays one argument. Quote variables at the call site the same way you quote them everywhere else.
Using All the Arguments: "$@" and "$*"
To process every argument, loop over "$@". The quotes matter. With them, each argument stays one item, even when it contains spaces:
show_each() { for a in "$@"; do echo "[$a]"; done; }
show_each "a b" c
[a b]
[c]
The other forms behave differently when given the same arguments "a b" and c:
star_each() { for a in $*; do echo "[$a]"; done; }
qstar_each() { for a in "$*"; do echo "[$a]"; done; }
star_each "a b" c
qstar_each "a b" c
[a]
[b]
[c]
[a b c]
An unquoted $* (or $@) is split again into words, so "a b" falls apart into a and b. A quoted "$*" joins everything into one string. Only the quoted "$@" keeps the original arguments intact. Use "$@" almost always, and "$*" only when you want one string, for example in a log message.
When there are no arguments, "$@" expands to nothing, so the loop runs zero times. An empty argument is still an argument:
none() { echo "args: $#"; for a in "$@"; do echo "loop ran"; done; }
none
none ""
args: 0
args: 1
loop ran
Function Arguments Hide the Script Arguments
A script has its own positional parameters (the arguments of the command line). While a function runs, $1, $2 and the others refer to the function's arguments. When the function returns, the script's parameters come back:
show_args() { echo "inside function: 1=[$1] 2=[$2] count=$#"; }
echo "script: 1=[$1] 2=[$2] count=$#"
show_args x y z
echo "script again: 1=[$1] 2=[$2] count=$#"
Run with bash scope89.sh first second:
script: 1=[first] 2=[second] count=2
inside function: 1=[x] 2=[y] count=3
script again: 1=[first] 2=[second] count=2
If a function needs the script's arguments, you must pass them on explicitly. The usual way is to hand over all of them with "$@":
main() { echo "main got $# args: $*"; }
main "$@"
Run with bash pass89.sh "a b" c d:
main got 3 args: a b c d
The script received three arguments (a b, c, d), and main received the same three, because "$@" preserved the grouping. This main "$@" pattern is common at the end of well-structured scripts (lesson 94).
Checking the Number of Arguments
A function should check that it has what it needs. The test $# (lesson 73) counts the arguments:
add() {
if [ "$#" -ne 2 ]; then
echo "usage: add NUMBER NUMBER" >&2
return 2
fi
echo $(( $1 + $2 ))
}
add 3 4
add 3; echo "status $?"
7
usage: add NUMBER NUMBER
status 2
The usage message goes to standard error (lesson 59), and return 2 reports the problem to the caller (lesson 90). Status 2 is the usual choice for wrong usage.
Default Values and Required Arguments
The parameter expansions from lesson 45 work on $1 and the other parameters:
hello() {
local who=${1:-World}
echo "Hello, $who"
}
hello
hello Ana
Hello, World
Hello, Ana
${1:-World} uses World when $1 is unset or empty. The local keyword (lesson 92) keeps who inside the function.
To make an argument required, use ${1:?message}. When the argument is missing, Bash prints the message, and a non-interactive shell stops with status 1. The example below runs the call in a subshell, so only the subshell stops:
need_one() {
local f=${1:?need a file name}
echo "using $f"
}
( need_one ); echo "subshell status $?"
bash: 1: need a file name
subshell status 1
The test run printed a script name and line number in front of the message (for example t89b.sh: line 2:); an interactive shell prints bash:. Without the subshell parentheses, the whole script ended at the failed call (the line echo "after call" after it was never run, and the status was 1), so use this form only when stopping the script is the intended reaction.
Checking the Value of an Argument
Arguments are always text. Bash has no numeric or boolean types, so the function must check that the text means what it expects. A regular-expression test with [[ ]] (lesson 69) works well for integers:
is_number() { [[ $1 =~ ^-?[0-9]+$ ]]; }
for v in 42 -7 3.5 abc ""; do
if is_number "$v"; then
echo "[$v] is an integer"
else
echo "[$v] is not an integer"
fi
done
[42] is an integer
[-7] is an integer
[3.5] is not an integer
[abc] is not an integer
[] is not an integer
The function body is only a test, so its exit status is the result. Callers can use it directly in an if (lesson 90). Without such a check, a text argument like abc would be read as a variable name inside $(( )) and silently counted as 0 (lesson 73).
Handling Any Number of Arguments
A loop over "$@" handles lists of any length:
total() {
local sum=0 n
for n in "$@"; do
sum=$((sum + n))
done
echo "sum of $# numbers: $sum"
}
total 5 10 15
total
sum of 3 numbers: 30
sum of 0 numbers: 0
With no arguments, the loop does not run and the sum stays 0.
Separating the First Argument with shift
The shift command (lesson 44) removes $1 and moves the others down by one. It is perfect when the first argument has a special meaning and the rest form a list:
log() {
local level=$1
shift
echo "[$level] $*"
}
log INFO server started on port 8080
log WARN disk almost full
[INFO] server started on port 8080
[WARN] disk almost full
After shift, $* holds everything except the level. A shift inside a function changes only the function's own parameters, never the script's.
The same is true for set --, which replaces all the positional parameters:
reset_args() { set -- new1 new2; echo "inside: $* ($#)"; }
set -- keep1 keep2 keep3
reset_args original
echo "outside: $* ($#)"
inside: new1 new2 (2)
outside: keep1 keep2 keep3 (3)
Passing an Array
You cannot pass an array as one value, but you can pass its elements as separate arguments with "${array[@]}" (lesson 104 shows more ways):
files=("my file.txt" "b.txt" "c.txt")
list() { printf '%s\n' "$@"; }
list "${files[@]}"
cnt() { echo $#; }
cnt "${files[@]}"
cnt ${files[@]}
my file.txt
b.txt
c.txt
3
4
The quoted form passes three arguments, and my file.txt stays whole. The unquoted ${files[@]} is split at the space, so the function receives four arguments. This is the same word-splitting problem as before, and the cure is the same: quote it.
Parsing Options Inside a Function
A function can accept options like a command does. The loop below reads options until it meets the first argument that is not an option, using case (lesson 75) and shift:
backup() {
local verbose=0 dest=/tmp
while (( $# > 0 )); do
case $1 in
-v) verbose=1; shift ;;
-d) dest=$2; shift 2 ;;
--) shift; break ;;
-*) echo "unknown option: $1" >&2; return 1 ;;
*) break ;;
esac
done
echo "verbose=$verbose dest=$dest files: $*"
}
backup -v -d /backups a.txt b.txt
backup a.txt
backup -x a.txt; echo "status $?"
backup -- -weird-name.txt
verbose=1 dest=/backups files: a.txt b.txt
verbose=0 dest=/tmp files: a.txt
unknown option: -x
status 1
verbose=0 dest=/tmp files: -weird-name.txt
The loop runs while arguments remain. -v sets a flag and shifts by one, -d takes the next word as its value and shifts by two, and -- ends the option list, which allows a file name that starts with a dash. The getopts command (lesson 130) is a ready-made tool for the same job, and lessons 127 to 133 cover argument parsing in depth.
Portability
Passing and reading arguments with $1, $#, "$@" and shift is POSIX and works in Dash. A test of $#, $*, a "b c" d and ${10} gave the expected results in Dash. The local keyword used in several examples is not part of the POSIX standard, even though Dash accepts it. The array and [[ =~ ]] examples need Bash.