1

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
2
  • 1
    just remove '()' Commented Jul 21, 2020 at 21:02
  • Thanks. Awesome! It works. Commented Jul 21, 2020 at 21:09

1 Answer 1

1

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]

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.