nantitv
nantitv

Reputation: 3733

global variable value not set inside a function in shell script

I have two shell script like as follows:

a.sh

tes=2
testfunction(){
    tes=3
    echo 5
}
testfunction
echo $tes 

b.sh

tes=2
testfunction(){
    tes=3
    echo 5
}
val=$(testfunction)
echo $tes
echo $val

In first script tes value is '3' as expected but in second it's 2?

Why is it behaving like this?

Is $(funcall) creating a new sub shell and executing the function? If yes, how can address this?

Upvotes: 5

Views: 14343

Answers (2)

ISanych
ISanych

Reputation: 22680

$() and `` create new shell and return output as a result.

Use 2 variables:

tes=2

testfunction() {
  tes=3
  tes_str="string result"
}

testfunction
echo $tes
echo $tes_str

output

3
string result

Upvotes: 4

user3442743
user3442743

Reputation:

Your current solution creates a subshell which will have its own variable that will be destroyed when it is terminated.

One way to counter this is to pass tes as a parameter, and then return* it using echo.

tes=2
testfunction(){
echo $1
}
val=$(testfunction $tes)
echo $tes
echo $val

You can also use the return command although i would advise against this as it is supposed to be used to for return codes, and as such only ranges from 0-255.Anything outside of that range will become 0

To return a string do the same thing

tes="i am a string"
testfunction(){
echo "$1 from in the function"
}
val=$(testfunction "$tes")
echo $tes
echo $val

Output

i am a string
i am a string from in the function

*Doesnt really return it, it just sends it to STDOUT in the subshell which is then assigned to val

Upvotes: 0

Related Questions