This question already has answers here:
A variable modified inside a while loop is not remembered

(8 个回答)


3年前关闭。




我想要一串我所有的 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 是空的。当我在循环内 echo $homepods 时,输出符合预期。

最佳答案

您可以使用以下脚本:-

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

echo $homepods

关于linux - 在循环外获取变量 linux bash,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51083309/

10-11 17:33