Ben Chuanlong Du's Blog

It is never too late to learn.

Functions in Bash

By default, variables defined in a function are global, i.e., they are visible outside the function too.

In [12]:
%%bash

function my_fun(){
    x=1
    x=2
    echo "Value of x inside the function: "$x
}

my_fun

echo "Value of x outside the function: "$x
Value of x inside the function: 2
Value of x outside the function: 2

Declaring a variable as local make it visible only in the function.

In [11]:
%%bash

function my_fun(){
    local x=1
    x=2
    echo "Value of x inside the function: "$x
}

my_fun

echo "Value of x outside the function: "$x
Value of x inside the function: 2
Value of x outside the function: 

You can declare a variable as local multiple times (which is different from other programming languages), but of course, only the first local declaration of a variable is necessary and the following local declaration of the same variable are useless and redundant.

In [13]:
%%bash

function my_fun(){
    local x=1
    local x=2
    echo "Value of x inside the function: "$x
}

my_fun

echo "Value of x outside the function: "$x
Value of x inside the function: 2
Value of x outside the function: 

If you have a global variable in a function and then declare it as local. The last value before it is declared as local is still visible outside the function.

In [14]:
%%bash

function my_fun(){
    x=1
    local x=2
    echo "Value of x inside the function: "$x
}

my_fun

echo "Value of x outside the function: "$x
Value of x inside the function: 2
Value of x outside the function: 1

By default, loop variables are global. However, you can declare them as local before using them.

In [17]:
%%bash

function my_fun(){
    for i in {1..3}; do
        echo $i
    done
    echo "Value of i inside the function: "$i
}

my_fun

echo "Value of i outside the function: "$i
1
2
3
Value of i inside the function: 3
Value of i outside the function: 3

In [19]:
%%bash

function my_fun(){
    local i
    for i in {1..3}; do
        echo $i
    done
    echo "Value of i inside the function: "$i
}

my_fun

echo "Value of i outside the function: "$i
1
2
3
Value of i inside the function: 3
Value of i outside the function: 

In [ ]:

Comments