ProDeveloperTutorial.com

Tutorials and Programming Solutions
Menu
  • Shell Scripting
  • System Design
  • Linux System Programming
  • 4g LTE
  • Coding questions
  • C
  • C++
  • DSA
  • GIT
  • 450 DSA Cracker
  • 5G NR
  • O-RAN

Shell Script Chapter 11: Shell Script Functions

prodevelopertutorial February 13, 2019

11.1 How to create a function?
11.2 How to call a function?
11.3 Function with no return value and no input arguments
11.4 Function with return value and no input arguments:
11.5 Function with input arguments
11.6 Nested Functions
11.7 Local Variables in function:
11.8 Read only functions.

A function is a way to break up a big program into smaller modules. By doing so the program will be easier to debug and easier to understand. It also helps to reuse the code.

11.1. How to create a function?

Syntax:

<function_name>()
{
#statements
}

Example:

exampleFunction()
{
echo "This is an example function"
}

11.2 How to call a function?

A function can be called by specifying it’s name.

Full example:

#!/bin/bash

#defining a function
fun()
{
echo "This is an example function"
}

#calling a function
fun

Output:

This is an example function

Below are the different types of function shell script supports:

11.3. Function with no return value and no input arguments

This is a simple function. It will not take input arguments and doesnt return any value.

Example:

#!/bin/bash

#defining a function
fun()
{
echo "This is a simple function"
}

#calling a function
fun

Output:

This is an example function

 

11.4. Function with return value and no input arguments:

In shell script, returning a value from a function can get tricky. Usually in shell script, “return” is considered as “exit” status. It takes value from 0 to 255. Hence to return a value use echo. And save the return value inside a variable while calling the function.

If your return value is 0 to 255 you can use “return” statement. Another point to note is, while returning a variable using “return” keyword, only integer value from 0 to 255 can be returned. String values cannot be returned.

Hence it is recommended to use echo command to return the values.

Example:

#!/bin/bash

#defining a function
fun()
{
return 1;
}

#calling a function
fun
var=$? #$? is used to get the previous value
echo "The return value using return keyword is $var"


fun_1()
{
echo "hello world"
}
#calling a function
var_1=$( fun_1 )

echo "The return value using echo keyword is $var_1"

Output:

The return value using return keyword is 1
The return value using echo keyword is hello world

11.5. Function with input arguments

In the previous example we saw how to correctly return a value from a function. In this example we shall see how to pass arguments to a function.

While calling the function you can specify the arguments as,

function_name “$arg1” “$arg2”

Then the function will identify the arguments by their position not by the name. i.e $1, $2, and so forth. $0 will be the name of the script itself.

Example:

#!/bin/bash

#defining a function
fun()
{
echo “The first variable is $1”
echo “The second variable is $2”
echo “The third variable is $3”
}

#calling a function with arguments
fun “1” “2” “3”

Output:

 

The first variable is 1
The second variable is 2
The third variable is 3

 

11.6. Nested Functions

Nesting is not same as we do it other languages. Nesting can be bit difficult at first. Below I have explained as simple as possible.
In shell script nesting can be done in 2 ways:

11.6.1 Method 1: True nesting

In this method, instead of using “{ }” use “( )”. By using this method, the inner function can be used inside the outer function. You cannot pass the inner function elsewhere.

Example:

#!/bin/bash

#defining a function
outer_function()
(
echo "In outer function"

inner_function()
{
echo "In Inner Function"
}

#calling inner function
inner_function
) #note we have used ( ) in outer function instead of { }

outer_function

Output:

In outer function
In Inner Function

11.6.2 Method 2: Indirect nesting

#!/bin/bash

one()
{
echo "One"
}

two ()
{
echo "Two"
}

#this can be considered as outer function.
three ()
{

echo "Three"

#calling the first two function
one
two
}

#calling third function
three

Output:

Three
One
Two

11.7 Local Variables in function:

In shell script, by default all the variables are global variables. Hence modifying a value inside a function will modify that variable globally. This will create issues. Hence to make a variable local to that function use “local” keyword.

Example:

#!/bin/bash

func_2()
{
global_var=20
echo "The value of global before change is $global_var"

local local_var=20
echo "The value of local variable is $local_var"
}
func_2

#manipulating the global variable outside the function
global_var=$(( $global_var+1 ))
echo "The value of global after change is $global_var"

 

Output:

The value of global before change is 20
The value of local variable is 20
The value of global after change is 21

As you can see from the output, even though we declare “global” variable inside the function, we can manipulate it outside the function also.

11.8 Read only functions.

We can make a function read-only by adding “readonly -f” option while calling a function. This is useful when you try to define another function which has already been defined.

Example:

#!/bin/bash

func_1()
{
echo "This is function 1"
}
readonly -f func_1

#calling func_1
func_1

#trying to define another function with same name

func_1()
{
echo "Defining function 1 another time"
}

Output:

This is function 1
18_function.c: line 17: func_1: readonly function

 

 

List Of Tutorials available in this website:

C Programming 20+ ChaptersC++ Programming 80+ Chapters
100+ Solved Coding QuestionsData Structures and Algorithms 85+ Chapters
System design 20+ ChaptersShell Scripting 12 Chapters
4g LTE 60+ ChaptersMost Frequently asked Coding questions
5G NR 50+ ChaptersLinux System Programming 20+ chapters
Share
Email
Tweet
Linkedin
Reddit
Stumble
Pinterest
Prev Article
Next Article

About The Author

prodevelopertutorial

Follow this blog to learn more about C, C++, Linux, Competitive Programming concepts, Data Structures.

Leave a Reply Cancel Reply

You must be logged in to post a comment.

ProDeveloperTutorial.com

Tutorials and Programming Solutions
Copyright © 2023 ProDeveloperTutorial.com
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept”, you consent to the use of ALL the cookies.
Do not sell my personal information.
Cookie SettingsAccept
Manage consent

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.
CookieDurationDescription
cookielawinfo-checkbox-analytics11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checkbox-functional11 monthsThe cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checkbox-necessary11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-others11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-performance11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
viewed_cookie_policy11 monthsThe cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.
Functional
Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
Performance
Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Analytics
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.
Advertisement
Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.
Others
Other uncategorized cookies are those that are being analyzed and have not been classified into a category as yet.
SAVE & ACCEPT