2019-03-14

Local variable in bash

Just a quick explanation on how local works in Bash I have been sending to somebody. Have this code:

$ cat /tmp/aaa 
function without_local() {
    variable1='hello'
    echo "Function without_local: $variable1"
}
function with_local() {
    local variable2='world'
    echo "Function with_local: $variable2"
}

echo "(1) variable1='$variable1'; variable2='$variable2'"
without_local
echo "(2) variable1='$variable1'; variable2='$variable2'"
with_local
echo "(3) variable1='$variable1'; variable2='$variable2'"

And run it and notice that variable1 behaves as global, variable2 wont leave function's context:

$ bash /tmp/aaa 
(1) variable1=''; variable2=''
Function without_local: hello
(2) variable1='hello'; variable2=''
Function with_local: world
(3) variable1='hello'; variable2=''