Saturday 15 February 2020

Functions and it significance in Linux scrpiting

Functions:


why functions:

  • Don't repeat the same lines of code again and again can be achieved.
  • Reduce of script length.
  • Maintenance of scripts in case of issue is easy with scripts. Because of single entry maintenance in entire script.
Thumb rules in the Function:

  • Must be defined before call.
  • Function syntax basically consists of two parts: 
                         1. defining function.
                         2. calling function.      
                                                                            
-----------------------------------------------------------------------------------------------------------------------
#Syntax for 1.defining function:


#Method-1
function function_name ( ) {

                      #code

}
-----------------------------------------------------------------------------------------------------------------------
#Method-2
function_name ( ) {

            #code
}

--------------------------------------------------------------------------------------------------------------------------


--------------------------------------------------------------------------------------------------------------------------
#2.calling function.  To call or execute the function which already defined,just mention #function_name  in the line of the script.

real time example:1
#!/bin/bash1

function hello(  ) {
echo "HELLO!!!"

}
hello                 #calling the function


output:

HELLO!!!



Real time example 2: with position parameters

#script     
#/bin/bash
function hello ( ) {
echo "hello $2"
}

hello ram sam zam                 # calling function

output:

hello sam

No comments:

Post a Comment