Linux 命令精选 -- Function 的调用方式会影响变量的作用域

可以在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##这里要去掉${}

转载于:https://my.oschina.net/frankies/blog/125414

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值