[英]Overriding a variable in two bash scripts
我必須猛擊腳本:
script1.sh
HELLO=hello
export HELLO
./script2.sh
echo $HELLO
script2.sh
echo $HELLO
HELLO=world
export $HELLO
輸出是hello hello
而不是hello world
。 如何在相互調用的腳本之間修改變量?
編輯:將變量作為參數傳遞將不起作用。 我不知道在script2.sh中可能更改的變量數量。
如果您不想將第二個腳本作為子進程運行,則必須為其提供源:
HELLO=hello
export HELLO
. ./script2.sh # Note the dot at the beginning
echo $HELLO
在第二個腳本中不需要導出-您已經告訴bash導出變量。
導出的變量在子外殼程序中可用(與script2.sh
和script1.sh
),但對父外殼程序不可用。
因此,由script1.sh
設置的變量在script2.sh
可用,但在script2.sh
返回時,在script2.sh
對其進行script2.sh
將不會使其在script1.sh
可用。
如果要將變量傳遞回調用者,則需要echo
它,並獲取script2.sh
的輸出。 但是,如果要查看其輸出,則需要script2.sh
寫入stderr:
script1.sh:
HELLO=hello
export HELLO
HELLO=$(./script2.sh)
echo >&2 $HELLO
script2.sh:
echo $HELLO >&2
HELLO=world
echo $HELLO
當您通過./script2.sh調用新腳本時,它將派生新shell,而當script2完成執行時,新shell將關閉。 當控件返回到腳本時,它的外殼仍然很舊,因此在script2中導出的變量將不可用。 要在同一shell中運行script2,您必須像“。./script2.sh”中那樣運行它
HELLO=hello
export HELLO
. ./script2.sh
echo $HELLO
script1.sh
的環境包含HELLO=hello
。 您在子script2.sh
所做的任何更改script2.sh
不會改變。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.