Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/shell/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 如何将数组传递到函数中以及对数组的更新反映在函数外部_Arrays_Shell_Debugging_Ubuntu_Command Line - Fatal编程技术网

Arrays 如何将数组传递到函数中以及对数组的更新反映在函数外部

Arrays 如何将数组传递到函数中以及对数组的更新反映在函数外部,arrays,shell,debugging,ubuntu,command-line,Arrays,Shell,Debugging,Ubuntu,Command Line,我试图将数组传递到函数中,对数组所做的任何更改都会反映在函数之外 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

我试图将数组传递到函数中,对数组所做的任何更改都会反映在函数之外

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) 如何对此索引数组进行更改,以使更改反映在函数外部

您可以通过在变量前面加一个
来迭代键

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

函数的定义应如下所示:

function update_array() {
    arr=("${!1}")
    arr[0]="abc"
}
然后称之为:

update_array "foo[@]"