Home > OS >  Print a string multiple times in bash based on condition
Print a string multiple times in bash based on condition

Time:02-16

This will list all the virtual networks in all the resource groups. A resource group can have multiple vnets. In that case i need to print the value of the resource group of every vnet. Currently i am getting the values of one to many as the result

rgNames=$(az group list --subscription <sub-name> --query [].name --output tsv)
for i in $rgNames; do
    vnet="$(az network vnet list -g $i --subscription <sub-name> --query [].name --output tsv)"
    echo $i,$vnet
done

Actual result

rg1,vnet1
rg2,vnet2 vnet3 vnet4
rg3,vnet5 vnet6

Expected result

rg1,vnet1
rg2,vnet2
rg2,vnet3
rg2,vnet4
rg3,vnet5
rg3,vnet6

Need the resource group names to be printed multiple times if it has multiple vnets.

CodePudding user response:

Loop over each vnet as well.

rgNames=$(az group list --subscription <sub-name> --query [].name --output tsv)

for i in $rgNames; do
    vnets="$(az network vnet list -g $i --subscription <sub-name> --query [].name --output tsv)"

    for vnet in $vnets; do
      echo "$i,$vnet"
    done
done

Also: Always doublequote variables to prevent globbing, word splitting etcc.

  • Related