Search code examples
bashfunctionglobal-variables

Using global variables in functions with parameters in bash


I'm trying to catch a return value from a function in bash, that modify a global variable. Works perfectly with funtions with no parameters:

#!/bin/bash

tes=2
testfunction(){
        tes=3
        tes_str="string result"
        return 0
}
if output=testfunction; then
        echo "OK"
else
        echo "KO"
fi
echo $tes
echo $tes_str

But no with parameters:

#!/bin/bash

tes=2
testfunction(){
        tes=3
        tes_str="string result"
        return 0
}
if output=$(testfunction "AA" "BB"); then
        echo "OK"
else
        echo "KO"
fi
echo $tes
echo $tes_str

Because for bash, parameters ("AA" or "BB") are a command, and I must put it in backets (but if use backets, can't modify global variables). How can I do it? I'm stucked. Regards


Solution

  • Why use output? Just remove it and run the function.

    if testfunction; then
    

    Notes:

    • output=testfunction is assigning the text testfunction to the variable output.
    • output=$(testfunction) will not work, because $(...) runs everything inside a subshell.