Function in shell script

DESCRIPTION: 
Function is the piece of code, which executed when we call.
When thinking about the function in any computer language, three points comes in mind

  1. Writing function code and calling that function when we need
  2. Passing arguments to the function
  3. Returning value from function

Next i going to elaborate about the 3 points i mentioned above 


FUNCTION CALL
Script shows below describe the simple function call. We should define the function before we using that 
  
script:                                                            
  #!/bin/bash    
  display(){          
       echo "This is inside function definition"    
  }    
  display #calling the display function 

output:
  This is inside function definition

PASSING ARGUMENT
Following scripts pass argument to function and display the argument value.

script:
#!/bin/bash

display_arg(){
    echo "first argument : $1"
    echo "second argument : $2"
}
display_arg "12" "sujin" #passing argument to function

output:  
first argument : 12
second argument : sujin
 
RETURNING VALUES
This script will shows how function return value to calling function

script:
#!/bin/bash

ret_val(){
    i="mystring"
    echo $i
}
x=$(ret_val)   #passing argument to function
echo "Returned Value : $x" 


output:
Returned Value : mystring


No comments:

Post a Comment