Bash: export not passing variables correctly to parent Bash: export not passing variables correctly to parent bash bash

Bash: export not passing variables correctly to parent


To access variable's in b.sh use source instead :

source b.sh var

It should give what you wanted.


Exporting variables in bash includes them in the environment of any child shells (subshells). There is however no way to access the environment of the parent shell.

As far as your problem is concerned, I would suggest writing $res only to stdout in b.sh, and capturing the output via subshell in a.sh, i.e. result=$( b.sh ). This approach comes closer to structured programming (you call a piece of code that returns a value) than using shared variables, and it is more readable and less error-prone.


Michael Jaros' solution is a better approach IMO. You can expand on it to pass any number of variable back to the parent using read:

b.sh

#!/bin/bashvar1="var1 stuff"var2="var2 stuff"echo "$var1;$var2"

a.sh

 IFS=";" read -r var1 var2 < <(./b.sh ); echo "var1=$var1" echo "var2=$var2"