0

I'm not exactly sure how to word the title, but what I am trying to do is to set username to $DEV_ENVIRONMENT, $STAGE_ENVIRONMENT, or $PROD_ENVIRONMENT respectively, each of which is defined in my properties file.

My function would take in one argument (DEV, STAGE, or PROD) and check the hostname against the edges defined in $_ENVIRONMENT.

while IFS=',' read -ra line
do
        for i in "${line[@]}"
        do
                if [ $(hostname) = $i ]
                then
                        username="$1"_USERNAME
                        break
                fi
        done
done <<< "${1}_ENVIRONMENT"

So for instance, if I pass in DEV, then I would like username set to $DEV_USERNAME and I'd like the while loop to search through the nodes defined in $DEV_ENVIRONMENT, both of which would be values read in from my properties file.

1 Answer 1

3

Bash supports indirection expansion, so you can do:

var=${1}_ENVIRONMENT
username=${!var}

rather than the slightly more cumbersome and potentially dangerous eval:

eval username=\$${1}_ENVIRONMENT

So for your code:

while IFS=',' read -ra line
do
        for i in "${line[@]}"
        do
                if [ $(hostname) = $i ]
                then
                        var="$1"_USERNAME
                        username=${!var}
                        break
                fi
        done
done <<< "${1}_ENVIRONMENT"
Sign up to request clarification or add additional context in comments.

6 Comments

Perfect! I'll accept your answer when it allows me, but would you mind expanding on the dangers of using the eval example you posted?
I was going to suggest eval or declare, but this solution works better.
eval allows you do do anything in the statement, so you could, for example have var="; echo evil"; eval user=\$$var would echo evil i.e. it's subject to value injection.
The eval command is extremely powerful and extremely easy to abuse. Examples of bad use of eval
BashFAQ #006 -- mywiki.wooledge.org/BashFAQ/006 -- might be another worthwhile reference.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.