Linux Shell Scripting Tutorial (LSST) v1.05r3 | ||
Passing parameter to user define function | Next | |
|
You can pass the parameter i.e. command line option to function as you passed to shell script. As you know you can define the function as follows:
function function-name( )
{
statement1
statement2
statementN
}
And you can call this function (without command line option) within the shell script as follows:
function-name
You can pass the parameter to function i.e. command line option to function as follows:
function-name arg1 arg2 arg3 argN
To clear you idea lets write shell script:
$ vi pass |
Run the above shell script as follows:
$ chmod +x pass
$ ./pass
All Arguments to function demo(): -f foo bar
First argument -f
Second argument foo
Third argument bar
As you can see the demo() function is define at the beginning of shell script. As you refer the command line args/option for shell script, same way you can refer the parameter for function. To pass the parameter to function we write it statement as follows in shell script:
demo -f foo bar
This statement passes three parameter to function demo -f, foo and bar. All of these parameters are stored to $1, $2, and $3 variable of function demo(). To clear your idea lets see one more example of parameter passing to function.
$ vi pass1 |
Run the above script as follows:
$ chmod +x pass1
$ ./pass1
5 + 10 = 15
10 - 2 = 8
10 / 2 = 5
5
Above script introduces some new concepts lets explore them step by step:
Command(s)/Statements | Explanation |
function cal() { | Begins the function definition for our cal() function |
n1=$1 op=$2 n2=$3 ans=0 | Stores the parameter passed to our function cal(). So if we called cal() as cal 5 + 10. Then store the values as follows: n1=5 op=+ n2=10 and ans to zero value. |
If [ $# -eq 3 ]; then ans=$(( $n1 $op $n2 )) echo "$n1 $op $n2 = $ans" return $ans | First see that sufficient parameter is passed or not. If sufficient parameter passed then do the calculation as per given operator on given two numbers. Then prints the calculation result using "echo $n1 $op $n2 = $ans" statement. return $ans statement is used to return the value of calculation. You can print this returned value using bashs built in variable $? |
else echo "Function cal requires atleast three args" fi return } | If sufficent parameter not given then print the message "Function cal requires atleast three args" and terminate the function cal(). |
cal 5 + 10 cal 10 - 2 cal 10 / 2 | Call the function cal to do different calculations. |
echo $? | Use to retrieve and print the value returned by cal(). Even you can store this value to variable by simply writing statement i=$?. |
Next | ||
Function | Up |