November 2024
M T W T F S S
 123
45678910
11121314151617
18192021222324
252627282930  

Categories

November 2024
M T W T F S S
 123
45678910
11121314151617
18192021222324
252627282930  

Function in shell script

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

Leave a Reply

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>