2014-09-11 45 views
1

在子脚本中导出的变量是不确定的父脚本(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}" 

儿童脚本(b.sh)看起来是这样的:

#!/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 

如果我现在运行使用./a.sh父,输出将是:

res = 5n 
result = 4n 

所以这里有一些舍入问题。任何人都知道为什么以及如何解决它?

+0

我想你想要做'./b.sh $ var',否则你提供字符串“var”到'b.sh'而不是变量'$ var'。 – fedorqui 2014-09-11 10:45:30

+2

这不是'export'应该做的事情。它将变量传递给子元素,无法在父元素中设置变量。 – Barmar 2014-09-11 10:46:58

回答

2

要访问的变量在b.sh使用source代替:

source b.sh var 

它应该给你想要的东西。

+1

与使用'相同。 ./b.sh var'? – Bjorn 2014-09-11 12:11:44

+0

'。 b.sh'是合适的。 '。/'只是指向当前目录。 – blackSmith 2014-09-11 12:14:56

+0

我确实似乎遇到问题。我只想将导出的变量传回给父项。在子脚本中定义的其他变量不应该影响父变量。这也是可能的吗? – Bjorn 2014-09-11 12:48:45

0

在bash中导出变量包括它们在任何子shell(subshel​​l)的环境中。然而,没有办法访问父shell的环境。

至于你的问题而言,我建议在b.sh$res只到stdout,并捕获由子shell的输出a.sh,即result=$(b.sh)。这种方法比使用共享变量更接近结构化编程(您称之为一段返回值的代码),并且它更具可读性并且不易出错。

+0

只要我使用'result = $(./ b.sh var)',这个工作就很好。但在这种情况下,必须确定结果是唯一的结果。然而,在我的完整代码中可能有多个输出,在这种情况下@blackSmith的答案更合适,更一致可用。 – Bjorn 2014-09-11 12:09:18