我在Cygwin bash版本4.3.42(4)中遇到了一个奇怪的(对我来说)问题.当在函数内调用前者时,在调用脚本中声明的Shell变量不会在调用脚本中保留.
我有以下两个脚本来说明问题.script1.sh调用script2.sh设置两个变量.如果通过script1中的函数调用script2,则变量将丢失,而如果在没有函数调用的情况下调用script2,则变量将按预期保持不变.所有对script2的调用都是通过"source"完成的.
script1.sh:
#!/usr/bin/bash # # calling script # function sourceit() { source scripts/script2.sh } sval=1 echo "$0 before sourceit(); rval=$rval sval=$sval PID=$$" sourceit echo "$0 after sourceit(); rval=$rval sval=$sval PID=$$" sval=3 echo "$0 before source; rval=$rval sval=$sval PID=$$" source scripts/script2.sh echo "$0 after source; rval=$rval sval=$sval PID=$$"
script2.sh
#!/usr/bin/bash # # called script # echo "$0 before declare; rval=$rval sval=$sval PID=$$" sval=2 declare -r rval=2 echo "$0 after declare; rval=$rval sval=$sval PID=$$"
结果:
scripts/script1.sh before sourceit(); rval= sval=1 PID=1752 scripts/script1.sh before declare; rval= sval=1 PID=1752 scripts/script1.sh after declare; rval=2 sval=2 PID=1752 scripts/script1.sh after sourceit(); rval= sval=2 PID=1752 scripts/script1.sh before source; rval= sval=3 PID=1752 scripts/script1.sh before declare; rval= sval=3 PID=1752 scripts/script1.sh after declare; rval=2 sval=2 PID=1752 scripts/script1.sh after source; rval=2 sval=2 PID=1752
我没有看到任何子壳被创建(到处都显示相同的PID).
我错过了一个更好的bash脚本点吗?