Sean
Sean

Reputation: 670

Iterate over column of output

I am trying to iterate over kubernetes namespaces so that I can print out the ip address of each ingress in each namespace.

Here's what's very strange. Running the commands in my shell works, but running the script does not work.

Basically, NAMESPACES=( $( echo $NAMESPACES ) ) only grabs the first item in the output when run from the script, whereas it grabs every line of output properly when run from my shell. So when the for loop runs it just iterates over one item.

I'm on a mac.

Can anyone identify how I should iterate over the column of namespaces? I list the output after the script. Thanks!

#!/bin/bash

# gcloud container clusters get-credentials $CLUSTER --zone $ZONE --project $PROJECT

# get just the column of namespace output
NAMESPACES=$(kubectl get namespace | awk '{print $1}' | tail -n +2)

# transpose the column into an array
NAMESPACES=( $( echo $NAMESPACES ) )

echo
echo "Printing out feature branch deployments and corresponding ip addresses:"
echo

for ns in $NAMESPACES
do
  # check if feature is in the namespace
  if [[ $ns == "feature-"* ]]
  then
    IP_ADDRESS=$(kubectl get ingress --namespace $ns | grep $ns | awk '{print $3}')
    echo $ns 'ip address:' $IP_ADDRESS
  fi
done

Here's what $NAMESPACES looks like

$ echo $NAMESPACES
chartmuseum 
default 
feature-1
feature-2 
feature-3
feature-4
feature-5
kube-public 
kube-system
qa
twistlock

# here's what $NAMESPACES looks like after it's transposed into the array
# this is what is iterated over in the for loop
$ echo $NAMESPACES
chartmuseum 
default feature-1 feature-2 feature-3 feature-4 feature-5 kube-public  kube-system qa twistlock

EDIT - Here's the answer: Just needed to comment out NAMESPACES=( $( echo $NAMESPACES ) ), and the script works. Thanks @bigdataolddriver

Upvotes: 2

Views: 3926

Answers (1)

Zlemini
Zlemini

Reputation: 4963

Try referencing the array with this syntax:

for ns in "${NAMESPACES[@]}"
do

done

Upvotes: 1

Related Questions