namerefs 和管道进入 bash

namerefs and piping into bash

当我也通过管道进入我的函数时,我无法让 bash namerefs 正常工作。

我在下面有一个函数,它接受一个 json blob 并将其转换为一个 bash 关联数组。由于 bash 不能按值传递关联数组,我编写了函数来接收 return 值的名称,已经 declared 成为一个关联数组。然后它为它设置一个 nameref 并写入它。

第一个示例有效:

jq_to_aa () {
  # takes a json hash as , and the name of a var in . Adds all entries from  into , via jq.

  local -n j2a_result=
  input="${@:2}"
  input=$(echo "$input" | jq -rM ". | to_entries | .[] | @text \"\(.key) \(.value)\"")

  while read -r key val; do
    j2a_result["$key"]="$val"
  done < <(echo "${input}")
}

data='{"a": 0.96}'
declare -A assoc=( )
jq_to_aa assoc "${data}"
echo expect 0.96: ${assoc[@]}

$ bash script1.sh expect 0.96: 0.96

好的,到目前为止一切顺利。但是,我希望函数通过管道接收数据。明显的变化是将其称为 echo "${data}" | jq_to_aa myvar,函数如下:

jq_to_aa () {
  # takes a json hash in stdin, and the name of an var in . Adds all entries from stdin into .

  input=$(jq -rM ". | to_entries | .[] | @text \"\(.key) \(.value)\"")

  local -n j2a_result=
  while read -r key val; do
    j2a_result["$key"]="$val"
  done < <(echo "${input}")
}

data='{"a": 0.96}'
declare -A assoc=( )
echo "${data}" | jq_to_aa assoc
echo expect 0.96: ${assoc[@]}

$ bash script2.sh expect 0.96:

这似乎不起作用,我正在努力寻找原因。我怀疑管道中的值会导致问题,也许是因为它创建了一个子外壳(是吗?我不知道)然后值被分开了。

为什么这不起作用,我该如何解决?

使用管道导致函数在子shell 中运行。 subshell 中的变量赋值不影响父 shell。请改用此处字符串。

jq_to_aa assoc <<<"$data"