Bash: export not passing variables correctly to parent

落花浮王杯 提交于 2019-12-07 13:22:54

问题


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?


回答1:


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

source b.sh var

It should give what you wanted.




回答2:


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.




回答3:


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"


来源:https://stackoverflow.com/questions/25785374/bash-export-not-passing-variables-correctly-to-parent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!