一千萬個為什麽

搜索

保存和恢復shell變量

我有兩個shell腳本,我想從C程序調用。我希望在第一個腳本中設置的shell變量在第二個腳本中可見。這是它的樣子:

灰:

var=blah

b.sh:


echo $var

The best I've come up with so far is a variant on "set > /tmp/vars" to save the variables and "eval $(cat /tmp/vars)" to restore them. The "eval" chokes when it tries to restore a read-only variable, so I need to grep those out. A list of these variables is available via "declare -r". But there are some vars which don't show up in this list, yet still can't be set in eval, e.g. BASH_ARGC. So I need to grep those out, too.

在這一點上,我的解決方案感覺非常脆弱且容易出錯,而且我不確定它是多麽便攜。有一個更好的方法嗎?

最佳答案

避免設置有問題變量的一種方法是僅存儲在每個腳本執行期間已更改的那些變量。例如,

灰:

set > /tmp/pre
foo=bar
set > /tmp/post
grep -v -F -f/tmp/pre /tmp/post > /tmp/vars

b.sh:

eval $(cat /tmp/vars)
echo $foo

/ tmp/vars包含:

PIPESTATUS=([0]="0")
_=
foo=bar

顯然,評估前兩行沒有任何不利影響。

轉載註明原文: 保存和恢復shell變量