Script Working With Function Arguments
Script Working With Function Arguments
Functions process variable values, or arguments, in much the same way as command line arguments. You don’t
declare the arguments as part of the function declaration. To understand how this works, consider the
following hello.sh script example:
#!/bin/bash
sayHello() {
sayHello "Amanda"
The name “Amanda” appears immediately after the function call to sayHello. As with command line arguments,
you access the value using $1 because $0 contains the function name. Two special symbols merit mention
when working with functions. The first, $#, provides the number of parameters sent to the function. The
second, $@, provides access to the parameters as a list. You employ them in a function as shown below:
#!/bin/bash
sayHello() {
for name in $@
do
echo $name
done
}
sayHello "Amanda" "Sam" "Mary" "James"
In the example above, the sayHello function receives four names. The function first outputs the number of
names, and then it processes each name individually using a for loop. The output looks like the following:
Amanda
Sam
Mary
James