arrays - 如何将数组传递给函数并且对数组的更新反射(reflect)在函数之外

标签 arrays shell debugging ubuntu command-line

我正在尝试将数组传递给函数,并且对数组所做的任何更改都会反射(reflect)在函数之外

function update_array()
{   
    ${1[0]}="abc" # trying to change zero-index array to "abc" , 
                  #  bad substitution error


}

foo=(foo bar)

update_array foo[@]

for i in ${foo[@]}
    do
       echo "$i" # currently changes are not reflected outside the function

    done

我的问题是

1)我如何访问索引数组,例如:零索引数组,在函数中,它的语法是什么

2)如何更改此索引数组,以便更改也反射(reflect)在函数外部

最佳答案

您可以通过在 var 前面加上 ! 来遍历键。 :

for key in ${!foo[@]}
do
  echo "$key: ${foo[$key]}"
done

至于更新数组,您不能将其传递给函数,但该函数可以访问脚本的全局状态,这意味着您可以这样做:
#!/bin/bash

function update_array() {
  foo[0]="bar"
}

foo=(foo bar)


for key in ${!foo[@]}
do
  echo "$key: ${foo[$key]}"
done
# 0: foo
# 1: bar

update_array

for key in ${!foo[@]}
do
  echo "$key: ${foo[$key]}"
done
# 0: bar
# 1: bar

关于arrays - 如何将数组传递给函数并且对数组的更新反射(reflect)在函数之外,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21026992/

相关文章:

bash - 在 bash shell 脚本中,如何将字符串转换为数字

c++ - 使用 libMallocDebug 调试内存泄漏

parsing - 忽略文件中的目录

arrays - 是否有返回两个子数组 : one of specified size and another of the remaining contents? 的 Ruby Array 方法

c++ - 打印一行二维字符数组 (C++)

javascript - jQuery 创建了新数组

linux - 需要使用 unix 脚本移动具有文件路径的目录中的文件名

.net - 调试托管应用程序崩溃

debugging - 没有工作台的 VxWorks 调试

python - numpy 中概率被忽略