Jasper
Jasper

Reputation: 161

Bash variable is not updated

Can someone explain to me why this simple example below does not work.

In this example, the "helper" function contains a different function as a parameter ("setV" and "getV"). Within the "setV" function, the value of the variable is updated. Still, the value within the "getV" function remains the old value. What is the reason for this?

vari="Oh no... I'm old."

function init() {
    helper setV
    helper getV
}
 
function helper() {
    ($1)
}
 
function setV() {
    vari="Hey! I'm new!"
}
 
function getV() {
    echo $vari
}
 
init

Upvotes: 1

Views: 560

Answers (1)

John1024
John1024

Reputation: 113994

The parens in ($1) cause $1 to be executed in a subshell. This means that any environment/variable changes are lost when the subshell exits.

Observe:

$ x=; setx() { x=Y; }; echo "1 x=$x"; (setx); echo "2 x=$x"; setx; echo "3 x=$x"
1 x=
2 x=
3 x=Y

If you want the variable changes to survive, don't put the command in a subshell.

Documentation

From man bash:

(list)
list is executed in a subshell environment (see COMMAND EXECUTION ENVIRONMENT below). Variable assignments and builtin commands that affect the shell's environment do not remain in effect after the command completes. The return status is the exit status of list. [Emphasis added]

Upvotes: 1

Related Questions