2012-07-24 63 views
1

我有打坏脚本变量:重写两个的bash脚本

script1.sh

HELLO=hello 
export HELLO 
./script2.sh 
echo $HELLO 

script2.sh

echo $HELLO 
HELLO=world 
export $HELLO 

输出是hello hello代替hello world。如何修改互相调用的脚本之间的变量?

编辑:作为参数传递变量将无法正常工作。我不知道可能在script2.sh中更改的变量数量。

回答

3

如果你不想运行第二个脚本作为一个子进程,你必须采购它:需要在第二个脚本

HELLO=hello 
export HELLO 
. ./script2.sh # Note the dot at the beginning 
echo $HELLO 

号出口 - 你已经告诉bash中导出的变量。

0

script1.sh环境包含HELLO=hello。你在孩子script2.sh中没有做什么会改变这一点。

1

导出的变量在子壳中可用(如script2.sh vs script1.sh),但不适用于父壳。

出于这个原因,由script1.sh设置变量是script2.sh可用,但在script2.sh设置也不会让它在script1.shscript2.sh回报可用。

如果你想将变量传回给调用者,你需要echo它,并抓取输出script2.sh。不过,你需要script2.sh写入标准错误,如果你想看到它的输出:

script1.sh:

HELLO=hello 
export HELLO 
HELLO=$(./script2.sh) 
echo >&2 $HELLO 

script2.sh:

echo $HELLO >&2 
HELLO=world 
echo $HELLO 
1

当U调用new脚本通过./script2.sh它会生成新的shell,而当script2完成执行时,新的shell将被关闭。当控制回来编写脚本时,它仍然是旧的shell,所以在script2中导出的变量将不可用。要运行在同一个shell SCRIPT2 u必须运行像 “./script2.sh”

HELLO=hello 
export HELLO 
. ./script2.sh 
echo $HELLO