0

I have a bash scripting question. I am trying to create the following code, however, it does not work properly. This leads me to wonder if it is even possible. I hope someone on here can figure it out.

MYSQL_DB_MyDatabase_USERS_username_PASSWORD=Password

DATABASE_NAME=MyDatabase
DATABASE_USER=username
DATABASE_PASS_TEMP=MYSQL_DB_${DATABASE_NAME}_USERS_${DATABASE_USER}_PASSWORD

echo $DATABASE_PASS_TEMP

I would want the output to be "Password" (the original variable). I am getting an error and I know I have incorrect syntax. I have googled around and found that using one variable in the variable name, one would use echo "${!DATABASE_PASS_TEMP}", but that does not work when using two dynamic variables. Thanks in advance for any help you can give.

2 Answers 2

2

Use BASH's variable indirection:

echo "${!DATABASE_PASS_TEMP}"
Password
Sign up to request clarification or add additional context in comments.

2 Comments

+1 Actually it is more known as variable indirection. But your answer is correct nonetheless.
Glad to know, can you mark the answer as accepted by clicking on tick mark on top-left of my answer.
0

Using an associative array would tidy things up some:

declare -A MYSQL_DB_PASSWORDS=(
    [MyDatabase,username]=Password
)

DATABASE_NAME=MyDatabase
DATABASE_USER=username

DATABASE_PASS_TEMP=${MYSQL_DB_PASSWORDS["$DATABASE_NAME","$DATABASE_USER"]}
echo "$DATABASE_PASS_TEMP"

Password

Comments

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.