bash 数组可以在用户定义的函数中声明为本地数组吗?确信 bash 数组始终具有全局作用域。
答案1
是的,数组可以是函数的局部数组。在函数内部用local
关键字声明它。这是一个示例脚本:
#!/usr/bin/env bash
global_ary=( one two )
function my_func () {
local local_ary=( three four )
echo "In my_func function:"
echo "global_ary: ${global_ary[@]}"
echo "local_ary: ${local_ary[@]}"
echo
}
echo "In main script:"
echo "global_ary: ${global_ary[@]}"
echo "local_ary: ${local_ary[@]}"
echo
my_func
echo "In main script again:"
echo "global_ary: ${global_ary[@]}"
echo "local_ary: ${local_ary[@]}"
echo
上面的脚本填充了一个全局数组和一个带有本地数组的函数。它在调用函数之前、期间和之后打印两个数组的内容。输出如下所示:
In main script:
global_ary: one two
local_ary:
In my_func function:
global_ary: one two
local_ary: three four
In main script again:
global_ary: one two
local_ary:
正如您所期望的,全局数组在主脚本和函数中可用。局部数组仅在函数中可用,因此只有echo "local_ary: ${local_ary[@]}"
函数中显示其内容。
作为实验,您可以将local
关键字更改为declare
或将其删除(将该行保留为local_ary=( three four )
)。这会导致local_ary
变量被创建为全局变量而不是局部变量。
答案2
#!/usr/bin/env bash
fun ()
{
local a=( 1 2 3 )
echo local "${a[@]}"
}
fun
echo global "${a[@]}" # empty