How to Use Functions in Bash Shell Scripts

Channel: Linux
Abstract: $2… etc. Create a shell script using following code. # vim script.shecho "First Argument

What is function:

A function which can also be referred to as subroutine, procedure is a block of code used for specific tasks. Function’s also have a property called reusability.

This tutorial will help you to how to create and use functions in shell scripts.

Create First Function in Shell Script

Create your first function in shell script showing output 「Hello World!」. Create a shell script 「script.sh」 using following code.

# vim script.sh
#!/bin/bash

funHello(){
    echo "Hello World!";
}

# Call funHello from any where in script like below

funHello

Execute Script

# sh script.sh
ouput:

Hello World!
How to Pass Arguments to Function in Shell Scripts

Passing argument to functions is something same like to pass argument to command from shell. Functions recieves arguments to $1,$2… etc. Create a shell script using following code.

# vim script.sh
#!/bin/bash

funArguments(){
   echo "First Argument : $1"
   echo "Second Argument : $2"
   echo "Third Argument : $3"
   echo "Fourth Argument : $4"
}

# Call funArguments from any where in script using parameters like below

funArguments First 2 3.5 Last

Execute Script

# sh script.sh
Ouput:

First Argument : First
Second Argument : 2
Third Argument : 3.5
Fourth Argument : Last

How to Receive Return Values from Functions in Shell Scripts

Some times we also need to return values from functions. Use below example to get returned values from functions in shell scripts.

# vim script.sh
#!/bin/bash

funReturnValues(){
echo "5"
}

# Call funReturnValues from any where in script and get return values

values=$(funReturnValues)
echo "Return value is : $values"

Execute Script

# sh script.sh
Ouput:

5
How to Create Recursive Functions in Shell Script

Functions which calls itself are called recursive functions. Following example is showing to print 1 to 5 digits with recursive function.

# vim script.sh
#!/bin/bash

funRecursive(){
val=$1
if [ $val -gt 5 ]
then
	exit 0
else
	echo $val
fi
val=$((val+1))
funRecursive $val     # Function calling itself here
}

# Call funRecursive from any where in script

funRecursive 1

Execute Script

# sh script.sh
Ouput:

1
2
3
4
5

Ref From: tecadmin

Related articles