0

当我也在输入我的函数时,我无法让 bash namerefs 正常工作。

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

第一个示例有效:

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

  local -n j2a_result=$1
  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 $1. Adds all entries from stdin into $1.

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

  local -n j2a_result=$1
  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:

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

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

4

1 回答 1

1

使用管道会导致函数在子 shell 中运行。子 shell 中的变量赋值不会影响父 shell。改用here-string。

jq_to_aa assoc <<<"$data"
于 2015-09-02T21:21:22.793 回答