4

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?

kojiro
  • 74,557
  • 19
  • 143
  • 201
nantitv
  • 3,539
  • 4
  • 38
  • 61
  • 6
    Yes `$(funcall)` creates a sub-shell. See http://stackoverflow.com/questions/23951346/is-there-a-subshell-created-when-i-run-sh-c-command-a-new-shell-or-none-of – damienfrancois Nov 05 '14 at 15:03
  • @damienfrancois how to solve this issue so that 'tes' should get the proper value as expected – nantitv Nov 05 '14 at 15:07

2 Answers2

4

$() 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
ISanych
  • 21,590
  • 4
  • 32
  • 52
0

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