hon*_*mu3 2 arrays parameters bash jq
我正在尝试修改我作为参数传递给函数的数组.到目前为止,我在函数外面有一个空数组:
buckets=()
Run Code Online (Sandbox Code Playgroud)
然后我有一个函数,它接受2个参数.第一个参数是我要填充的空数组.第二个参数是包含我要用于填充数组的数据的文件的名称.
到目前为止,我所做的是创建一个临时数组.然后用文件的内容填充临时数组.这就是我这样做的方式:
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)
Run Code Online (Sandbox Code Playgroud)
最后一步是将参数数组(又名桶)设置为我们刚刚填充的临时数组的内容.关于如何做到这一点的任何建议?
在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")
}
Run Code Online (Sandbox Code Playgroud)
然后将其称为:
buckets=()
fillarray buckets file.json
Run Code Online (Sandbox Code Playgroud)
并将其测试为:
declare -p buckets
Run Code Online (Sandbox Code Playgroud)
编辑:要使其在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")
}
Run Code Online (Sandbox Code Playgroud)
然后将其称为:
buckets=()
fillarray buckets ${#buckets[@]} file.json
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1201 次 |
| 最近记录: |