1

I would like to take each line of the output of one gcloud command for use in another gcloud command.

gcloud container clusters list |grep jesse (alias gccl) output:

jesse-gke1                us-eastx-x
jesse-gke2                us-eastx-x

I need both of these variables (name and region) in the next command.

But when I try to use awk to get the variables I need for the next command, it combines both results into a single variable with 2 lines.

cluster=$(gccl 2>/dev/null|grep jesse|awk '{print $1}') ; echo $cluster

Outputs:

jesse-gke1
jesse-gke2

How can I get both of the output items in a command that would look like:

gcloud someaction jesse-gke1 zone=us-eastx-x

and iterate through the results?

Thanks!

2
  • 1
    Just a supposition...Did you really remove the double quotation marks from the last command? Meaning echo $cluster instead of echo "$cluster". When you require your shell to perform word splitting then quotes are not needed.
    – marc
    Feb 14, 2022 at 14:12
  • Does awk take args from stdin? Try putting xargs in your pipeline just before awk, or just replacing awk in your command with xargs /full/path/to/awk
    – Nate T
    Feb 14, 2022 at 14:15

1 Answer 1

2
#!/bin/sh

gcloud container clusters list \
    --filter=name:jesse --format="csv[no-heading](name,location)" |
while IFS=, read -r name location; do
    printf 'Resizing NAME: %s, LOCATION: %s\n' "$name" "$location"
    gcloud container clusters resize \
        --zone "$location" "$name" --num-nodes=0 --quiet
done >gccl-script.log

This is a rewrite of your own code, using a while loop rather than a for loop. The while loop is used whenever we need to read an indeterminate number of lines in a loop, whereas a for loop is used for iterating over a static list.

We also don't need an array as read is perfectly happy to read multiple fields into multiple variables.

We use printf rather than echo to print variable data. The result of echo depends on the current state of the shell and on the data outputted.

We can move the redirection of the loop's output to after done.

We need to properly quote all expansions to avoid splitting and filename globbing from happening.

I'm using lower-case variable names.

Relevant other questions:

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .