在循环外获取变量Linux bash

时间:2018-06-28 12:45:10

标签: linux bash

我想要一个所有HomePod ID的字符串。我可以循环播放一个名为player.json的文件:

homepods=""
jq -r '.data.players[]|select(.type == "airplay" and .is_multiple == false)|.id' players.json | while read homepod; do
    homepods+="$homepod,"
done

echo $homepods

我希望结果为id,id,id,但是$ homepods为空。当我在循环内回显$ homepods时,输出将如预期的那样。

2 个答案:

答案 0 :(得分:2)

您可以使用以下脚本:-

homepods=""
for homepod in `jq -r '.data.players[]|select(.type == "airplay" and .is_multiple == false)|.id' players.json` ; do
    homepods+="$homepod,";
done

echo $homepods

答案 1 :(得分:1)

管道在具有父流程环境副本的新环境中启动新流程,因此无法更改父变量。

因此,您需要另一种方法:

homepods=$( 
    printf "%s," $(
    jq -r '.data.players[]|select(.type == "airplay" and .is_multiple == false)|.id' players.json
))

在这种情况下,父级会捕获子级的输出。

或者:

homepods=$(
  jq -r '.data.players[]|select(.type == "airplay" and .is_multiple == false)|.id' players.json | while read homepod; do
    echo "$homepod,"
  done)

回答您的其他请求:您还可以回显计数器,然后将其与捕获的输出分离。但是,还有一种更简单的选择:

homepods_array=(${homepods//,/ })
homepods_count=${#homepods_array[@]}

将字符串转换为bash array,然后恢复数组的长度。那也使用bash字符串操作来替换空格的逗号。

顺便说一句,使用字符串操作,您可以获得多种格式的ID,而根本没有循环:

homepods_lines=$(jq -r '.data.players[]|select(.type == "airplay" and .is_multiple == false)|.id' players.json)
homepods_spaces=${homepods_lines//$'\n'/ }
homepods_commas=${homepods_lines//$'\n'/,}
homepods_array=(homepods_lines)
homepods_count=${#homepods_array[@]}