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?
In BASH 4.3+ you can just pass an array by named reference. So your function can be simplified to:
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")
}
Then call it as:
buckets=()
fillarray buckets file.json
And test it as:
declare -p buckets
EDIT: To make it work on BASH 3.2 use below snippet:
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")
}
Then call it as:
buckets=()
fillarray buckets ${#buckets[@]} file.json
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With