bash中的声明-u是否也使变量具有本地作用域



我对这个示例脚本的输出感到困惑。当我将some_other_var声明为大写(declare-u(时,它似乎被隐式声明为本地:

#!/bin/bash
function works() {
some_var="${1}"
printf "in the function, some_var is ${some_var}n"
}
function doesnt_work() {
declare -u some_other_var="${1}"
printf "in the function, some_other_var is ${some_other_var}n"
}
works "apple"
printf "got back this value of some_var from the function: ${some_var}n"
doesnt_work "banana"
printf "got back this value of some_other_var from the function: ${some_other_var}n"

输出:

in the function, some_var is apple
got back this value of some_var from the function: apple
in the function, some_other_var is BANANA
got back this value of some_other_var from the function: 

declare-u应该只使变量大写,它确实做到了。但是,它是否也应该使变量具有局部作用域?我的印象是,必须使用"local"指令将变量明确标记为local,否则它是全局的,但declare-u的行为似乎不同。

这是:

GNU bash, version 4.2.46(2)-release (x86_64-redhat-linux-gnu)

这是declare的一个通用属性:在函数中使用时,它意味着局部作用域。要使用全局作用域,必须使用-g标志(Bash 4.2+(。

参见手册:

在函数中使用时,除非使用了-g选项,否则declare会使每个名称成为本地名称,与local命令一样。

最新更新