3

I am trying modify an array that I have passed as a parameter to a function. So far, I have an empty array outside of the function:

buckets=()

Then I have the function which takes in 2 arguments. The first argument is the empty array that I want to fill. The second argument is the name of the file that contains the data I want to use to fill the array.

So far, what I have done is create a temporary array. Then fill the temporary array with the contents of the file. This is how I do that:

fillarray ()
{
# Declare the paramater as a temporary array
declare -a tempArray=("${!1}")

# Fill it up
while IFS= read -r entry; do
  tempArray+=("$entry")
done < <(jq -r '.data | .[].name' $2)

The final step is to set the parameter array(aka buckets) to be the contents of the temporary array which we just filled up. Any suggestions on how to go about doing this?

4

2 回答 2

7

BASH 4.3+中,您可以通过命名引用传递一个数组。所以你的功能可以简化为:

fillarray() {
   # tempArray is a reference to array name in $1
   local -n tempArray="$1"
   while IFS= read -r entry; do
      tempArray+=("$entry")
   done < <(jq -r '.data | .[].name' "$2")
}

然后将其称为:

buckets=()
fillarray buckets file.json

并将其测试为:

declare -p buckets

编辑:要使其在BASH 3.2上运行,请使用以下代码段:

fillarray() {
   # $2 is current length of the array
   i=$2
   while IFS= read -r entry; do
      read ${1}"[$i]" <<< "$entry"
      ((i++))
   done < <(jq -r '.data | .[].name' "$3")
}

然后将其称为:

buckets=()
fillarray buckets ${#buckets[@]} file.json
于 2015-01-29T20:17:08.723 回答
0

通过另一种方式eval

fillarray () {
 local tempArray;

 while IFS= read -r entry; do
    tempArray[${#tempArray[@]}]="$entry";
 done < <(jq -r '.data | .[].name' $2);

 eval $1=\('"${tempArray[@]}"'\);
}
于 2015-01-29T23:03:55.900 回答