Thursday, 7 January 2016

How Function Works In Unix/Linux Scripting

In this article we will see
  • How to create functions in Unix scripting
  • How to call function in Unix scripting
  • How to pass parameter in functions
We will see syntax of each and will implement function with the help of an example.

1. How to create functions and call them in Unix/Linux scripts

SYNTAX: 

Function_Name () {
   #--Unix Commands [OR] Operations
}


[OR]

function Function_Name () {
   #--Unix Commands [OR] Operations
}


Both are valid syntax in unix. Let see a example script Function_Tutorial.sh which uses functions.

$ cat Function_Tutorial.sh

#!bin/sh
function f_Example
{
   echo "We are inside the function"
}
echo "We are in Main script"

#-------------------
#--*Calling Function
#-------------------

f_Example
echo "We are again in Main script"


$ sh Function_Tutorial.sh

Output:
We are in Main script
We are inside the function
We are again in Main script



Explanation:

  • !bin/sh in first line, meaning that the script should always be run with sh, rather than another shell.  /bin/sh is an executable representing the system shell.
  • When shell executes the scripts it skips the function and read echo command and print it on console. In next line it call the function f_Example (this is how functions are called) hence echo command of function has executed. Once function execution is done, control comes out of the function and next line is executed hence last echo statement has executed.
  • Please note when you are using function keyword you don't need to provide () but when you are not using function keyword then need to use () with function name.
 f_Example() {
  echo "We are inside the function"
 }


2. How to pass parameter to the functions in unix script.

We have already seen how to pass parameter to shell script, same concept is applicable for function as well. I would suggest to visit the post Positional Parameter In Unix/Linux Scripts  before you start this section.
let see how it works.

$ cat greatest_num.sh

#!bin/sh
function f_greatest_num
 

 #----------------------------------------------------
 #--* Assigning the function parameter to the variables
 #----------------------------------------------------

 V_First_Num=${1} 

 V_Second_Num=${2}
 V_Third_Num=${3}


  if [[ ${V_First_Num} -gt ${V_Second_Num}

     && ${V_First_Num} -gt ${V_Third_Num} ]]  
  then
        echo "Greatest Number is ${V_First_Num}";  

  elif [[ ${V_Second_Num} -gt ${V_First_Num}
       && ${V_Second_Num} -gt ${V_Third_Num} ]]
  then
        echo "Greatest Number is ${V_Second_Num}";  

  else
        echo "Greatest Number is ${V_Third_Num}";
  fi
}
echo "-----------------------------------------------
"
echo " ****** Function To Find Largest Number *******"
echo "-----------------------------------------------"
#-------------------
#--*Calling Function
#-------------------

f_greatest_num


$ sh greatest_num.sh

Output: As we have not provided any parameter hence we have not received any output.
-----------------------------------------------
 ****** Function To Find Largest Number *******
-----------------------------------------------
Greatest Number is


lets provide parameter to the script, below is the syntax to provide parameter to the script.

SYNTAX: shell_Script.sh <parm1> <parm2> <parm3> ... <parmN>

$ sh greatest_num.sh 6 8 9

Output: Still we have received Same output.
-----------------------------------------------
 ****** Function To Find Largest Number *******
-----------------------------------------------
Greatest Number is


This is the time to introduce SCOPE of the parameter in shell script as well as in function.
A parameter passed to script will be available in script only and will not be available for function inside the same script. Let rewrite our script.

$ cat greatest_num.sh

#!bin/sh
function f_greatest_num
{

 #----------------------------------------------------
 #--* Assigning the function parameter to the variables
 #----------------------------------------------------

 V_First_Num=${1}
 V_Second_Num=${2}  

 V_Third_Num=${3}

  if [[ ${V_First_Num} -gt ${V_Second_Num}
     && ${V_First_Num} -gt ${V_Third_Num} ]]  

  then
        echo "Greatest Number is ${V_First_Num}";  

  elif [[ ${V_Second_Num} -gt ${V_First_Num}
       && ${V_Second_Num} -gt ${V_Third_Num} ]]
  then
        echo "Greatest Number is ${V_Second_Num}";  

  else
        echo "Greatest Number is ${V_Third_Num}";
  fi


}
echo "-----------------------------------------------"
echo " ****** Function To Find Largest Number *******"
echo "-----------------------------------------------"
echo "1st Parameter is" ${1}
echo "2nd Parameter is" ${2}

echo "3rd Parameter is" ${3}
#-------------------
#--*Calling Function
#-------------------

f_greatest_num ${1} ${2} ${3}


$ sh greatest_num.sh 6 8 9

Output: This time we have received the correct result as shown below.
-----------------------------------------------
 ****** Function To Find Largest Number *******
-----------------------------------------------
1st Parameter is 4
2nd Parameter is 5
3rd Parameter is 6
Greatest Number is 6



Still this script is not the correct script as there might be a possibility that user would not provide required 3 parameter, in such cases script will not provide any fruitful result. lets again rewrite the script.

$ cat greatest_num.sh

#!bin/sh
function f_greatest_num

 #----------------------------------------------------
 #--* Assigning the function parameter to the variables
 #----------------------------------------------------

 V_First_Num=${1}
 V_Second_Num=${2} 

 V_Third_Num=${3}
 

  if [[ ${V_First_Num} -gt ${V_Second_Num}
     && ${V_First_Num} -gt ${V_Third_Num} ]]  

  then
        echo "Greatest Number is ${V_First_Num}";  

  elif [[ ${V_Second_Num} -gt ${V_First_Num}
       && ${V_Second_Num} -gt ${V_Third_Num} ]]
  then
        echo "Greatest Number is ${V_Second_Num}";  

  else
        echo "Greatest Number is ${V_Third_Num}";
  fi

}
echo "-----------------------------------------------"
echo " ****** Function To Find Largest Number *******"
echo "-----------------------------------------------"

V_First_Param=${1}
V_Second_Param=${2}
V_Third_Param=${3}

#--------------------------------
#--* Validating script Parameters
#--------------------------------

if [ $# -eq 3 ]then
#-------------------
#--*Calling Function
#-------------------

 f_greatest_num ${V_First_Param} ${V_Second_Param} ${V_Third_Param}
else
 echo "This Script Needs 3 Parameter, please provide the same to continue" 

exit;
fi


$ sh greatest_num.sh


Output: Observe the output, This time we have received an notification from program that you have not provided required parameter. By using $# we are making sure that user must provide all the required parameter. This is how we use $# to validate the parameter in real time scripting.

-----------------------------------------------
 ****** Function To Find Largest Number *******
-----------------------------------------------
This Script Needs 3 Parameter, please provide the same to continue



Note: We should avoid the usage of ${1}, ${2} ...${n}  directly in scripting as it creates complexity when you have multiple functions. We should always hold/assign the parameter (${1}, ${2} ...${n}) in user defined variables to enhance the code readability. See how  V_First_Param, V_Second_Param, V_Third_Param are used to hold the 3 script parameter and the same is then passed as parameter to function f_greatest_num.


Conclusion: Whenever you want your peace of code should be used in multiple places put it in FUNCTION. Function provides modularity, re usability and clarity in understanding of the code.

Keep Reading, Keep Learning, Keep Sharing...!!

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...