tak89
tak89

Reputation: 13

Bash: Update the parent variable from function variable

i want to update the variable a become 2. But the result is always 1. Is there anyway to do it?

a=1
aple(){
        a=2
        echo "apel"
}
b=`aple`
echo $a

Upvotes: 1

Views: 124

Answers (1)

anubhava
anubhava

Reputation: 785008

Problem is in this call:

b=`aple`

Which invokes aple function in a subshell hence changes made in subshell are lost and not visible in the parent shell.

Call your function as:

aple
echo $a
2

As per your comments if you want to assign a value to b also then have your function as:

a=1
b=
aple() { a=2; b="apel"; }

Then call it as:

aple
echo "$b:$a"
apel:2

Upvotes: 1

Related Questions