Bash gotcha: function variable scope

Posted: 11th October 2015 by Tim in Bash, Linux
Tags: , , , , , , ,

Consider the following bash script:

#!/usr/bin/env bash

function myFunc
{
    myvar=123
    echo "myFunc: setting myvar=$myvar"
}

myvar=1
echo "before myFunc: myvar=$myvar"
myFunc
echo "after myFunc: myvar=$myvar"

The code here is fairly simple – we set a variable myvar, call a function and print the value of myvar to the terminal. However, even though we don’t pass myvar to the function, that value is still changed:

before myFunc: myvar=1
myFunc: setting myvar=123
after myFunc: myvar=123

Somehow, myFunc changed the value of myvar. This is because, unless specified otherwise, this variable is in the global scope. This can sometimes be useful, but it can also be confusing for programmers used to the scoping rules of other languages.

To keep myvar contained to function scope only, we can use the local keyword like so:

function myFunc
{
    local myvar=123
    echo "myFunc: setting myvar=$myvar"
}

With this specified, the code behaves more like we would expect:

before myFunc: myvar=1
myFunc: setting myvar=123
after myFunc: myvar=1