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.

  • .csh with a #!/bin/bash hashbang? You may want to check that naming. – ilkkachu Feb 7 '18 at 18:15
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[@]

  • I added quotes around the ${!cur_env}, so values can have spaces if desired etc. – XrXca Feb 6 '18 at 23:37
  • This works perfectly! Thank you very much for you help. I'm not familiar with indirect variables so I will look these up. Thanks again! – need_java Feb 6 '18 at 23:41
  • @XrXca: You shouldn't only quote variables "so values can have spaces". You should always quote variables. Security implications of forgetting to quote a variable in bash/POSIX shells – Jesse_b Feb 6 '18 at 23:45
  • Note that associative array keys aren't stored in the order you declare them, so the for loop isn't guaranteed to go in dev->test->prod order. Not sure if this is an issue in this case, just pointing this out. – m0dular Feb 7 '18 at 17:33
  • 1
    @m0dular, there's no associative arrays here, just regular integer-indexed ones. Bash 3 doesn't even support them, and that's what the OP said they're stuck with. – ilkkachu Feb 7 '18 at 18:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.