Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over column of output

Tags:

bash

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

like image 259
Sean Avatar asked Oct 30 '25 18:10

Sean


1 Answers

Try referencing the array with this syntax:

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

done
like image 198
Zlemini Avatar answered Nov 02 '25 12:11

Zlemini



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!