【问题标题】:Bash Command grouping on nested while loops嵌套 while 循环上的 Bash 命令分组
【发布时间】:2021-02-15 16:07:50
【问题描述】:

如何使用命令分组来修改以下脚本的全局变量“数据”?

metrics='{"names":["metric1","metric12"]}'

data="{\"metrics\":["

echo "${metrics}" | ./jq -r ".names[]" |
while IFS=$'\t' read -r name; do
  metric=$(curl "https://localhost/..../${name}")
  tagName=$(echo "${metric}" | ./jq -r ".availableTags[0].tag")

  echo "${metric}" | ./jq -r ".availableTags[0].values[]"  |
  while IFS=$'\t' read -r tagValue; do
      metricResult=$(curl "https://localhost/...../${name}?tag=${tagName}:${tagValue}")
      metricName="BAL BLA BLA"
      metricValue=$(echo "${metricResult}" | ./jq ".measurements[0].value")

      metricJson="{\"metric\":\"${metricName}\",\"metricValue\":${metricValue}},"
     
      data="${data}${metricJson}"
  done

done

echo "${data}"

据我了解,每个 while 循环都在子 shell 中执行,因此不会修改全局“数据”变量。 我正在考虑使用command grouping,但到目前为止还没有运气。

编辑

我尝试了以下方法,但它不起作用:

while IFS=$'\t' read -r name; do
  echo "######## ${name}"
 
  while IFS=" " read -r tagValue; do
    #.....  
  done <<< $(echo "${metric}" | ./jq -r ".availableTags[0].values[]")

done <<< $(echo "${metrics}" | ./jq -r ".names[]")

现在 while 循环不起作用,echo ${name} 的输出是 metric1 metric12。我尝试使用此 IFS=' ' read -r .. 或此 IFS= read -r .. 但变量 name 仍然不包含单个指标,而是包含所有指标

【问题讨论】:

  • 希望您的解决方案在这里:unix.stackexchange.com/questions/402750/… ?
  • 换句话说,重定向来自echo "${metrics}" | ./jq -r ".names[]" 的输入。
  • 这看起来很复杂,我不会用 bash 编写它,而是用 Python、Ruby、Perl 或 NodeJS 编写。如果您有 jq 和 curl,那么您肯定也有其中一种更合适的脚本语言。
  • @Roadowl 我试过了,但似乎这个while IFS=$'\t' 不再工作了......我会继续寻找解决它的方法。或许你有什么建议?
  • @Thomas 不幸的是,这是一个受控环境,python 没有安装也无法安装

标签: linux bash jq


【解决方案1】:

这应该可行:

#!/usr/bin/env bash
  
metrics='{"names":["metric1","metric12"]}'

data="{\"metrics\":["

while IFS=$'\t' read -r name; do
  metric=$(curl "https://localhost/..../${name}")
  tagName=$(echo "${metric}" | ./jq -r ".availableTags[0].tag")

  while IFS=$'\t' read -r tagValue; do
      metricResult=$(curl "https://localhost/...../${name}?tag=${tagName}:${tagValue}")
      metricName="BAL BLA BLA"
      metricValue=$(echo "${metricResult}" | ./jq ".measurements[0].value")

      metricJson="{\"metric\":\"${metricName}\",\"metricValue\":${metricValue}},"
     
      data="${data}${metricJson}"
  done < <(echo "${metric}" | ./jq -r ".availableTags[0].values[]")

done < <(echo "${metrics}" | ./jq -r ".names[]")

echo "${data}"

【讨论】:

    【解决方案2】:

    不要使用&lt;&lt;&lt; $(...),而是使用:&lt; &lt;(...)

    【讨论】:

      猜你喜欢
      • 2016-05-13
      • 1970-01-01
      • 2014-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多