Unix Tutorial 13 : Functions
Syntax for defining functions:
function_name()
{
…
<statements>
…
}
To invoke a function, simply use the function name as a command.
Example:
$ function_name
To pass parameters to the function, add space separated arguments like other commands.
Example:
$ function_name $arg1 $arg2 $arg3
The passed parameters can be accessed inside the function using the standard positional variables i.e. $0, $1, $2, $3 etc.
Example:
function_name()
{
…
c = $1 + $2
…
}
Functions can return values using any one of the three methods:
#1) Change the state of a variable or variables.
#2) Use the return command to end the function and return the supplied value to the calling section of the shell script.
Example:
function_name()
{
echo “hello $1”
return 1
}
Running the function with a single parameter will echo the value.
$ function_name ram
hello ram
Capturing the return value (stored in $?) as follows:
$ echo $?
1
#3) Capture the output echoed to the stdout.
Example:
$ var = `function_nameram`
$ echo $var
hello ram
Comments
Post a Comment