2

I am still new to Bash and can only use Bash 3 at work. I'm trying to build a process that will allow me to connect to all of our databases (DEV/TEST/PROD).

I have a file named environments.sh

#!/bin/bash
## 0 = Password, 1 = HOST, 2 = SERVICENAME

## List of all Environments
ENV[0]=DEV
ENV[1]=TEST
ENV[2]=PROD

## Dev Env Details
DEV[0]=SU_DBA_201503
DEV[1]=xxxxxx-Dev-xx.xxx.xxx.xxx  #<-- I edited this for security purposes
DEV[2]=dev.xxx.xxx 

## Test Env Details
TEST[0]=DBA_PN_0002
TEST[1]=xxxxxx-Test-xx.xxx.xxx.xxx
TEST[2]=test.xxx.xxx

## Prod Env Details
PROD[0]=TM_DB_US7a6a
PROD[1]=xxxxxx-Prod-xx.xxx.xxx.xxx
PROD[2]=prod.xxx.xxx

So essentially, my goal is to loop through all environments (DEV, TEST, PROD) and access each array's attributes to build a connection string.

At this point I have a new file (for testing purposes, I've callit it looper.csh:

#!/bin/bash

#Get environments
source ./environments.sh

for env in ${ENV[@]}
do
    echo Current Env $env
    cur_env=$env
    for attr in ${cur_env[@]}
    do
    # Will eventually build connection string but for now, just want to echo
        echo $attr
    done
done

But when I run this, it gives me an error on the line:

for attr in ${cur_env[@]}

I've tried a few different ways to substitute this correctly, but I'm not sure what I'm doing wrong.

Any and all guidance would be greatly appreciated.

ilkkachu
  • 138,973

1 Answers1

2

I'd suggest indirect variable references:

source ./environments.sh

for env in "${ENV[@]}"
do
    cur_env="${env}[@]"
    for attr in "${!cur_env}"
    do
        # whatever
    done
done

Note the ! before the cur_env in the for attr, it means use the value of the variable named in this var which on the first round will be DEV[@]

ilkkachu
  • 138,973
XrXca
  • 119