5

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?

2
  • 6
    Yes $(funcall) creates a sub-shell. See stackoverflow.com/questions/23951346/… Commented Nov 5, 2014 at 15:03
  • @damienfrancois how to solve this issue so that 'tes' should get the proper value as expected Commented Nov 5, 2014 at 15:07

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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

3 Comments

is there a way to return string from a function
@nantitv yes the exact same way

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.