所以我有一个执行此操作的脚本(jq是命令行JSON处理器):
echo "Getting LB Node IDs"
echo $LB_STATUS | jq '.loadBalancer.nodes[] .id'
最后一行的输出是:
1
2
3
但是当我尝试将它分配给一个数组时:
echo "Creating an Array"
nodeIdArray=($($LB_STATUS | jq '.loadBalancer.nodes[] .id'))
我收到此错误:
./myShellScript.sh: line 53: {"loadBalancer":{"name":"lbName","id":1,"protocol":"HTTP","port":80,"algorithm":"WEIGHTED_LEAST_CONNECTIONS","status":"ACTIVE","cluster":{"name":"ztm-n22.dfw1.lbaas.rackspace.net"},"nodes":[{"address":"1.2.3.4","id":1,"type":"PRIMARY","port":80,"status":"ONLINE","condition":"ENABLED","weight":1},{"address":"1.2.3.4","id":2,"type":"PRIMARY","port":80,"status":"ONLINE","condition":"ENABLED","weight":1},{"address":"1.2.3.4","id":3,"type":"PRIMARY","port":80,"status":"ONLINE","condition":"ENABLED","weight":1}],"timeout":30,"created":{"time":"2016-06-28T22:14:24Z"},"healthMonitor":{"type":"CONNECT","delay":10,"timeout":5,"attemptsBeforeDeactivation":2},"sslTermination":...<A BOAT LOAD MORE JSON I CUT OUT FOR BREVITY'S SAKE>: File name too long
SO $ LB_STATUS | jq'.loadBalancer.nodes [] .id'在尝试将这些数字分配给数组时产生一些数字不起作用
答案 0 :(得分:4)
$variable | something
未将variable
中的文字作为something
的输入传递 - 相反,它会将$variable
的内容作为命令运行。大概你想要echo "$variable" | something
代替(但见下文!)
即使修复了问题,array=( $(some-command) )
成语本身就是错误的。请参阅BashPitfalls #50,说明不应该使用它的原因,以及各种替代方案。
当从变量中提供内容作为命令的输入时,使用herestring:somecommand <<<"$variable"
是惯用的。这些不是免费的(因为它们创建了临时文件),但它们比管道便宜(它可以分解子套)。
如果你有b或4.x或更新,你有readarray
:
readarray -t nodeIdArray < <(jq -r '.loadBalancer.nodes[].id' <<<"$LB_STATUS")
如果您需要与bash 3.x兼容,read -a
可以完成这项工作:
IFS=$'\n' read -r -d '' -a nodeIdArray \
< <(jq -r '.loadBalancer.nodes[].id' <<<"$LB_STATUS" && printf '\0')
...如果read
命令失败,它还具有导致jq
返回非零退出状态的优势。
答案 1 :(得分:3)
您遗漏了echo
。
更改
nodeIdArray=($($LB_STATUS | jq '.loadBalancer.nodes[] .id'))
到
nodeIdArray=($( echo $LB_STATUS | jq '.loadBalancer.nodes[] .id' ))