How to Modify a Global Variable Within a Function in Bash

Nilesh Katuwal Feb 02, 2024
How to Modify a Global Variable Within a Function in Bash

In this article, we will learn about modifying a global variable within a function in Bash.

Modify Global Variable Within a Function in Bash

If you declare your variables inside a script, every variable in Bash will be global by default, which means that it will be accessible to any function, script, and even the outside shell.

If you declare a variable within a function to be global, you can access its value even while the function is not being executed.

Any variable you declare is a global variable by default. If you define a variable outside of the function, you will not encounter any issues when using it inside the function.

Code Example:

e=2
 function example1() {
   a=4
   echo "Today"
 }
 example1
 echo "$a"

Output:

Today
4

On the other hand, if we assign the result of the function to a variable, the value of the global variable a would not be altered.

Code Example:

 a=2
 function example1() {
   a=4
   echo "Today"
 }
 ret=$(example1)
 echo "$ret"
 echo "$a"

Output:

Today
 2

Related Article - Bash Variable