0% found this document useful (0 votes)
8 views

Script Working With Function Arguments

Copyright
© © All Rights Reserved
Available Formats
Download as ODT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Script Working With Function Arguments

Copyright
© © All Rights Reserved
Available Formats
Download as ODT, PDF, TXT or read online on Scribd
You are on page 1/ 2

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() {

echo "Hello $1"

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() {

echo "There are $# names to process."

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:

There are 4 names to process.

Amanda

Sam

Mary

James

Return Values from Functions

You might also like