We use the function
keyword to declare functions in UNIX/Linux, as shown below:
_functionName_()
{
//function body
}
_functionName_
: name of the function.function body
: statements written within a function.To call a function, write its name where you want to call the function:
_functionName_
To add input parameters to a function, write the parameters after the name of the function where it is called:
_functionName_ _param1_ _param2_
_param1_
and _param2_
are the input parameters.
To return a value from a function, use the return
keyword followed by the return value.
Note: The function will not execute any statements written in the function after the return statement.
Consider the code snippet below, which demonstrates the implementation of a simple function to print “Hello world!!” on screen.
printFunction () { echo "Hello world!!" } printFunction #calling the function
Consider this example of a function that takes input parameters.
greetFunction () { echo "Hello $1!! How are you?" } greetFunction Ali #calling the function
Ali
is the input parameter to the function greetFunction
. $1
in line 2 is used to reference the value of the input parameter.
Consider this example of a function that takes two numbers and returns their sum.
sumFunction () { return $(($1+$2)) } sumFunction 2 5 #calling the function sum=$? #getting return value of function echo "2 + 5 = $sum"
RELATED TAGS
CONTRIBUTOR
View all Courses