Variable scope

By default, any variable you declare inside a function is a global variable. That means this variable can be used outside and inside the function without problems.

Check out this example:

#!/bin/bash 
myvar=10 
myfunc() { 
   myvar=50 
} 
myfunc 
echo $myvar 
 

If you run this script, it will return 50, which is the value changed inside the function.

What if you want to declare a variable that is exclusive to the function? This is called a local variable.

You can declare local variables by using the local command like this:

myfunc() { 
   local myvar=10 
} 

To ensure that the variable is used only inside the function, let's check out the following example:

#!/bin/bash 
myvar=30 
myfunc() { 
   local myvar=10 
} 
myfunc 
echo $myvar 

If you run this script, it will print 30, which means that the local version of the variable is different than the global version.