【问题标题】:namerefs and piping into bashnamerefs 和管道进入 bash
【发布时间】:2015-09-02 21:15:43
【问题描述】:

当我也在管道中输入我的函数时,我无法让 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:

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

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

【问题讨论】:

  • 当你使用管道时,函数在子shell中运行。子shell中的变量赋值不会影响原来的shell进程。

标签: linux bash shell bash4


【解决方案1】:

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

jq_to_aa assoc <<<"$data"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-13
    • 1970-01-01
    • 2016-06-18
    • 2013-05-05
    • 1970-01-01
    • 1970-01-01
    • 2013-10-31
    • 2012-01-28
    相关资源
    最近更新 更多