How to modify a global variable within a function in bash?

When you use a command substitution (i.e., the $(...) construct), you are creating a subshell. Subshells inherit variables from their parent shells, but this only works one way: A subshell cannot modify the environment of its parent shell.

Your variable e is set within a subshell, but not the parent shell. There are two ways to pass values from a subshell to its parent. First, you can output something to stdout, then capture it with a command substitution:

myfunc() {
    echo "Hello"
}

var="$(myfunc)"

echo "$var"

The above outputs:

Hello

For a numerical value in the range of 0 through 255, you can use return to pass the number as the exit status:

mysecondfunc() {
    echo "Hello"
    return 4
}

var="$(mysecondfunc)"
num_var=$?

echo "$var - num is $num_var"

This outputs:

Hello - num is 4

Leave a Comment