Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 8

Unit 3

Advanced Bash Shell Scripting


Function:
A function is a collection of statements that execute a
specified task. Its main goal is to break down a
complicated procedure into simpler subroutines that can
subsequently be used to accomplish the more complex
routine.For the following reasons, functions are popular:
• Assist with code reuse.
• Enhance the program’s readability.
• Modularize the software.
• Allow for easy maintenance.
• The basic structure of a function in shell scripting looks as
follows:

function_name()
{
// body of the function
}
Example
• Following example shows the use of function −
#!/bin/sh
# Define your function here
Display ()
{
echo "Hello World"
}
# Invoke your function Display
Pass Parameter to Function
#!/bin/sh
# Define your function here

Display ()
{
echo "Hello World $1 $2"
}

$./test.sh Display rishi rahul


Returning Values from Functions
display()
{
echo "Hello World $1 $2"
return 10
}
# Invoke your function
display Rishi Rahul
# Capture value returnd by last command
ret=$?
echo "Return value is $ret"
Nested Functions
Display1()
{
echo “First function"
Display2
}
Display2()
{
echo "second function “
}
Display1
Sum of Two Numbers
Display1()
{
x=10
y=10
c=$[$x+$y]
echo “sum is : $c”
}
Display1

You might also like