可以在bash中执行以下脚本,名为test4.sh:
#!/bin/bash
function test1() {
RUNTIME_INITI_CFG="test"
}
function t1() {
test1
echo Hello,$RUNTIME_INITI_CFG
}
function t2() {
$(test1)
echo Bad,$RUNTIME_INITI_CFG
}
echo "$(t1)"
echo "$(t2)"
结果:
[root]$ ./test4.sh
Hello,test
Bad,
总结: 由于linux 中对于函数的调用方式可以为“ <Function name> [...args]” 也可以为"$(<Function name> [...args])", 前者在函数调用之前所有的全局将会应用到函数中并影响调用之后的,即是全局的。而后者就涉及到变量作用域的问题。因此,如果你想让某些变量全局可访问(可读可写)的话,就要注意这种情况,这几天搞脚本之后才发现的这个规律!为了让全局变量全局有效,因此建议修改成以下三个种方式实现:
第1种:
#!/bin/bash
function test1() {
RUNTIME_INITI_CFG="test"
}
function t1() {
test1 ##这里要去掉${}
echo Hello,$RUNTIME_INITI_CFG
}
function t2() {
test1 ##这里要去掉 ${}
echo Bad,$RUNTIME_INITI_CFG
}
echo "$(t1)"
echo "$(t2)"
第2种:
#!/bin/bash
function test1() {
RUNTIME_INITI_CFG="test"
}
function t1() {
test1 ##这里要去掉${}
echo Hello,$RUNTIME_INITI_CFG
}
function t2() {
test1 ##这里要去掉${}
echo Bad,$RUNTIME_INITI_CFG
}
t1 ##这里要去掉${}
echo "$(t2)"
第3种:
#!/bin/bash
function test1() {
RUNTIME_INITI_CFG="test"
}
function t1() {
test1 ##这里要去掉${}
echo Hello,$RUNTIME_INITI_CFG
}
function t2() {
test1 ##这里要去掉${}
echo Bad,$RUNTIME_INITI_CFG
}
t1 ##这里要去掉${}
t2##这里要去掉${}