2014-09-11 46 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