2016-06-14 131 views
0

我有一個shell腳本parent.sh像這樣。我希望變量標誌child.sh使用,更新標誌的價值那裏得到更新值回parent.sh。我怎樣才能做到這一點。訪問和更新其他腳本中的shell腳本變量

#!/bin/bash 
flag=999  #I want ths flag in child.sh and there i will update its value depending on some condition 
$HOME/child.sh 
if [ $? -eq $flag ];then #The value of flag got changed on child.sh 
echo "Success" 
else 
echo "Failed" 
fi 

而且我child.sh如下

#!/bin/bash 
hive -f $HOME/creat.hql   #It should be create.hql so it will fail. 
if [ $? -eq 0 ];then 
    flag=0 
else 
    flag=1  #This will execute and I want this change to be get reflected in parent.sh 
fi 
+0

你爲什麼要使用child.sh的返回值以及更改的標誌變量?你可以簡單地把'exit $ flag'放在child.sh的末尾,然後使用'if [$ flag -eq 0];然後回聲「成功」'... –

+0

我如何能在_child.sh_ – MrG

+0

使用'標誌= $訪問的變量_flag_?'電話後,直接讓你有返回值(你用'$退出在flag'設置劇本)。您不使用腳本中的標誌值,但您具有相同的值(假設值只能是0-127)。我的意思是說'如果[$? -eq 0];然後......在我上面的評論中回顯「成功」,但將退出值賦值給一個變量更安全,如果你希望那也可以稱爲'flag' –

回答

0

您需要sourcechild.shparent.sh以便它在當前子shell執行:

#!/bin/bash 
flag=999  #I want ths flag in child.sh and there i will update its value depending on some condition 
. ./child.sh 
if [ $? -eq $flag ];then #The value of flag got changed on child.sh 
echo "Success" 
else 
echo "Failed" 
fi 

你可以檢查flag正確的價值在採購child.sh後確保其正確設置在child.sh之內。有關source如何工作的更多信息,請參見或help .裏面的bash

+0

_source_使_child.sh_中的所有命令執行,我不想要。我只想訪問和使用_flag_變量 – MrG

+0

我認爲你不能這樣做。每個腳本都是在一個單獨的bash過程中執行的,孩子無法修改其父代的環境。 –