Search code examples
bashglobal-variables

How to modify a global variable within a function and return a boolean in bash?


I'm working with this:

GNU bash, version 4.4.20(1)-release (x86_64-pc-linux-gnu)

I have a script like below:

#!/bin/bash

map2=()
result=""
f() {
    tmpA=(12 34 7844);
    map2=("${tmpA[@]}");
    echo true;
    return;
}

result=$(f)
echo result=$result : array=${map2[@]}

Which returns:

result=true : array=

if I replace result=$(f) simply by f it returns:

result= : array=12 34 7844

I could not find the way to modify the global array but also get the return value. Any idea on how to achieve this?


Solution

  • Any environment changes made inside $( ... ) are lost when it exits.

    However, bash allows a way of changing arguments passed "by reference" by using the declare -n command:

    #!/bin/bash
    
    map2=()
    result=""
    f() {
        declare -n resultRef=$1
        declare -n map2Ref=$2
    
        local tmpA=(12 34 7844)
        map2Ref=("${tmpA[@]}")
        map2Ref[4]=999
        resultRef=true
    
        echo during: resultRef=$resultRef : arrayRef=${map2Ref[*]} : tmpA=${tmpA[*]}
    }
    
    f result map2
    
    echo after: resultRef=$resultRef : arrayRef=${map2Ref[*]} : tmpA=${tmpA[*]}
    echo result=$result : array=${map2[*]}
    

    Variables declared in this way behave like local - they are discarded when the function returns.

    during: resultRef=true : arrayRef=12 34 7844 999 : tmpA=12 34 7844
    after: resultRef= : arrayRef= : tmpA=
    result=true : array=12 34 7844 999