我有以下两个脚本来说明问题. 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脚本点吗?
I have the following two scripts to illustrate the issue. script1.sh calls script2.sh which sets two variables. If script2 is invoked via a function in script1,the variables are lost,
不,你的输出显示变量rval的值在从函数返回后丢失,但变量sval的值被保留.
whereas if script2 is invoked without the function call,the variables persist as expected. All invocations of script2 are done via “source”.
由于rval和sval的行为之间存在区别,因此您应该在script2.sh中查看它们的处理方式的差异,etvoilà!事实证明,rval通过内置声明赋值,而sval直接赋值.查看声明的文档,然后,我们发现:
When used in a function,makes each name local,as with the
local
command.
bash中的局部变量就像大多数其他语言中的局部变量一样 – 它们与其他具有相同名称的变量不同,并且在它们的范围内它们影响来自包含范围的命名变量.因此,在每种情况下,您的代码在任何地方设置和检查相同的变量sval,但它设置并检查函数内部的rval,而不是其他任何地方.