Module-9-How to create and use  functions in bash scripting

Table of contents

Introduction

We can create functions to avoid writing repetitive lines of codes just like other scripting languages in Bash , but the functionalities available is less when compared to python

Syntax to create function in Bash 

Following are the different possible syntax we can use to  create a function and call it in the script 

 function func_name {
command_statements
}

or

func_name () {
command_statements
}

or


func_name() { command_statements ; }

Practical example on creating and using the function in bash scripts 

In the following example we have created a script which uses all the 3 types of syntax to create the function . Each function packs just a one command statement echo. To call the function in the script , we need to declare it first and then we can use the function_name just like every other command in bash script 

#script 
[root@discoveringsystems Bash-functions]# cat bash-function-script
#!/bin/bash

function first_function () {

echo "this is a first test function"
}

first_function

second_function() { echo "this is the second test function" ;}

second_function

third_function ()
{
echo "this is the third function"
}

third_function
#script execution 
[root@discoveringsystems Bash-functions]# ./bash-function-script
this is a first test function
this is the second test function
this is the third function

Leave a Comment

Your email address will not be published. Required fields are marked *