Search code examples
bashgcloud

`gcloud builds list` can't capture command output in variable


I have some working code which follows the pattern seen below.

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

Check output with: $FIRST_BILLING_ACCOUNT

Prints my billing account's name.

And like this:

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

Check output with: $REGION

Prints the region.

Problem

This does not work:

OUT=$(gcloud builds list --ongoing)

It prints the output: Listed 0 items. and does not save the value in $OUT.

Other things which do not work, pulled from here: How do I redirect output to a variable in shell?

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

gcloud builds list --ongoing | read OUT

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

I even tried this:

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

And it had the same result.

I want to know 2 things: How do I capture this command's output? And why do different gcloud commands seem to behave differently?


Solution

  • I just figured it out. It's printing to STDERR instead of STDOUT. To capture:

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

    I'll just have to use 2>&1 in all of my checks from now on.