linux下如何取消只读变量,在bash中取消设置readonly变量

F. Hauri..

5

但是使用更简单的语法:

gdb -ex 'call unbind_variable("PI")' --pid=$$ --batch

经过改进的功能:

我的destroy功能:

或如何使用可变的元数据。注意罕见bashisms的用法:local -n VARIABLE=$1和${VARIABLE@a}...

destroy () {

local -n variable=$1

declare -p $1 &>/dev/null || return -1 # Return if variable not exist

local reslne result flags=${variable@a}

[ -z "$flags" ] || [ "${flags//*r*}" ] && {

unset $1 # Don't run gdb if variable is not readonly.

return $?

}

while read resline; do

[ "$resline" ] && [ -z "${resline%\$1 = *}" ] &&

result=${resline##*1 = }

done <

gdb 2>&1 -ex 'call unbind_variable("'$1'")' --pid=$$ --batch

)

return $result

}

您可以将其复制到名为的bash源文件中destroy.bash,作为示例...

说明:

1 destroy () {

2 local -n variable=$1

3 declare -p $1 &>/dev/null || return -1 # Return if variable not exist

4 local reslne result flags=${variable@a}

5 [ -z "$flags" ] || [ "${flags//*r*}" ] && {

6 unset $1 # Don't run gdb if variable is not readonly.

7 return $?

8 }

9 while read resline; do

10 [ "$resline" ] && [ -z "${resline%\$1 = *}" ] &&

11 result=${resline##*1 = }

12 done <

13 gdb 2>&1 -ex 'call unbind_variable("'$1'")' --pid=$$ --batch

14 )

15 return $result

16 }

第2行创建对提交变量的本地引用。

第3行防止在不存在的变量上运行

第4行将参数的属性(meta)存储到中$flags。

第5至8行将运行,unset而不是gdb如果不存在readonly标志

线9至12 while read ... result= ... done的获取返回代码call unbind的gdb输出

第13行gdb使用--pid和的语法--ex(请参阅参考资料gdb --help)。

第15行返回$result的call unbind命令。

正在使用:

source destroy.bash

# 1st with any regular (read-write) variable:

declare PI=$(bc -l <<

echo $PI

3.14159265358979323844

echo ${PI@a} # flags

declare -p PI

declare -- PI="3.14159265358979323844"

destroy PI

echo $?

0

declare -p PI

bash: declare: PI: not found

# now with read only variable:

declare -r PI=$(bc -l <<

declare -p PI

declare -r PI="3.14159265358979323844"

echo ${PI@a} # flags

r

unset PI

bash: unset: PI: cannot unset: readonly variable

destroy PI

echo $?

0

declare -p PI

bash: declare: PI: not found

# and with non existant variable

destroy PI

echo $?

255

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值