首页 > 解决方案 > `gcloud builds list` 无法在变量中捕获命令输出

问题描述

我有一些工作代码遵循下面的模式。

FIRST_BILLING_ACCOUNT=$(gcloud beta billing accounts list --filter=open=true --format="value(name)" --limit=1)

检查输出:$FIRST_BILLING_ACCOUNT

打印我的帐单帐户名称。

像这样:

REGION=$(gcloud app describe --format="value(locationId.scope())")

检查输出:$REGION

打印区域。

问题

这不起作用:

OUT=$(gcloud builds list --ongoing)

它打印输出:Listed 0 items.并且不将值保存在 $OUT 中。

其他不起作用的东西,从这里拉出来:如何将输出重定向到 shell 中的变量?

OUT="$(gcloud builds list --ongoing)"

gcloud builds list --ongoing | read OUT

read OUT < <(gcloud builds list --ongoing)

我什至试过这个:

echo "gcloud builds list --ongoing" >> tst.sh
chmod +x tst.sh
OUT=$(./tst.sh)
$OUT

它有同样的结果。

我想知道两件事:如何捕获此命令的输出?为什么不同的 gcloud 命令似乎表现不同?

标签: bashgcloud

解决方案


我刚刚想通了。它打印到 STDERR 而不是 STDOUT。捕捉:

OUT=$(gcloud builds list --ongoing 2>&1)

从现在开始,我只需要使用2>&1我所有的支票。


推荐阅读