linux - Bash 函数局部数组变量在调用位置不可访问

标签 linux bash shell

有2个bash脚本文件。下面提到了第一个文件 b.sh

#!/bin/bash
declare -a arr1=()
func() {
    var_a=12
    arr1[0]=20
    arr1[1]=30
    declare -a arr2=()
    arr2[0]=40
    arr2[1]=50
}

下面提到了第二个文件a.sh

#!/bin/bash
source b.sh
func
echo $var_a
echo ${arr1[1]}
echo ${arr2[1]}

输出为

12
30

我的疑问是,为什么func中的局部数组变量(arr2)在a.sh中无法访问。但局部变量 var_a 是可以访问的。

最佳答案

arr2 是一个局部变量,因为它是使用 declare 创建的。如 Bash Manual 中所述:

When used in a function, declare makes each name local, as with the local command, unless the -g option is used.

由于您没有使用 declare 创建 var_a,因此赋值会创建一个全局变量,因此可以在函数外部访问它。如果你写的是:

declare var_a=12

local var_a=12

在函数内部,那么它就是本地的。

关于linux - Bash 函数局部数组变量在调用位置不可访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48450897/

相关文章:

C++ Apache 模块 : Fails on `_ZNSs4_Rep20_S_empty_rep_storageE`

linux - lsof linux 命令使用参数值计算正在运行的实例

用于获取(最新)文件的 python 代码,其中时间戳作为名称附加到电子邮件

bash - 如何在单独的自动变量中获得这些结果?

ios - 如何从命令行获取 NSUserDefaults

python - Python:subprocess.call错误“找不到命令”

linux - 在 linux 中过滤文本输出

c++ - linux c/c++ - 奇怪的 if/else 问题

linux - 如何在 Telnet bash 脚本中设置超时?

linux - bash ping ip 回复时运行命令