Bjorn
Bjorn

Reputation: 313

Bash: export not passing variables correctly to parent

The variables exported in a child-script are undefined the parent-script (a.sh):

#!/bin/bash
# This is the parent script: a.sh
export var="5e-9"
./b.sh var
export result=$res;  # $res is defined and recognized in b.sh
echo "result = ${result}"

The child-script (b.sh) looks like this:

#!/bin/bash
# This is the child script: b.sh
# This script has to convert exponential notation to SI-notation
var1=$1
value=${!1}
exp=${value#*e}
reduced_val=${value%[eE]*}
if [ $exp -ge -3 ] || [ $exp -lt 0 ]; then SI="m";
elif [ $exp -ge -6 ] || [ $exp -lt -3 ]; then SI="u";
elif[ $exp -ge -9 ] || [ $exp -lt -6 ]; then SI="n";
fi

export res=${reduced_val}${SI}
echo res = $res

If I now run the parent using ./a.sh, the output will be:

res = 5n
result = 4n

So there is some rounding problem going on here. Anybody any idea why and how to fix it?

Upvotes: 4

Views: 7582

Answers (3)

Rondo
Rondo

Reputation: 3721

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/bash
var1="var1 stuff"
var2="var2 stuff"
echo "$var1;$var2"

a.sh

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

Upvotes: 0

Michael Jaros
Michael Jaros

Reputation: 4681

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.

Upvotes: 3

blackSmith
blackSmith

Reputation: 3154

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

source b.sh var

It should give what you wanted.

Upvotes: 6

Related Questions