Tutorial: Function in Bash Shell Scripting with Examples(v4.2)


In this tutorial, I will go through the function in bash shell scripting with examples. Bash function is basically a set of commands that can be called number of times. The very purpose of a function is to help reuse the same logic multiple times. Compared to other programming languages, Bash functions are little different and can be used in a limited way.

Function in Bash Shell

What is Function

Functions in Bash are usually a set of commands to perform a particular task. So whenever you call a function in your script, execution will jump into that function and will resume from same place once the function execution completes.

Why do we need function

a)It reuses the functionality efficiently.
b)It Improve the readability of a program.
c)Same variables can be used locally in every function.
d)It allows a Complex functionality to be divided into smaller tasks.

Tutorial: Function in Bash Shell Scripting with Examples(v4.2) 1


function fname {





Variables in Bash Functions

Every variable we use has a scope, the scope is variable visibility to your script.
You can define two types of variables:


Global Variables

They are visible and valid anywhere in the bash script. You can even get its value from inside the function.If you declare a global variable within a function, you can get its value from outside the function.
Any variable you declare is a global variable by default. If you define a variable outside the function, you call it inside the function without problems:


func1() {
    val=$(($val + 20))
read -p "Enter a number: " val
echo "The new value is: $val"

Local Variables

If you will use the variable inside the function only, you can declare it as a local variable using the local keyword like this:

local tmp=$(( $val + 10 ))

So if you have two variables, one inside the function and the other is outside the function and they have the identical name, they won’t affect each other.


func1() {
     local tmp=$(($val + 10))
     echo "The variable from inside function is $temp"
echo "The variable from outside is $tmp"

Also Read: How to print array in Bash Scripts

Reference: Bash Shell Script

Leave a Comment