How to reference a shell variable named by another shell variable

Have you ever had the need to get the value of a shell variable, but the name was all, or partly, determined by another shell variable. That happened to me this week and once you know how to do it it is pretty simple, but it is hard to figure it out.

I’ll try to clarify. I have a shell variable that has been set with a password. To find that variable I have another variable. The second variable is the User Name and is called USER. The first is the password and is called USERPW. (Note: I’m not saying this is the best way to handle passwords, it is what I had to work with.)

In a given situation I’ll need the password for a user that is provided by the variable USER. I thought I could get this in a variety of ways:

$${USER}pw}
${${USER}PW}

etc…

To end the story and give you what you came looking for. Here is the solution (in a test script):

->cat deref.ksh
#!/bin/bash
export USER=MYUSER
export USERPW=
. /somewhere/pwds.sh # this script sets environment variables with passwords
echo echo deference
eval USERPW=\$${USER}PW
echo ${USER}
echo ${USERPW}
sqlplus -s ${USER}/${USERPW} << eof
show user
eof

Here is the output that shows it worked. The last line is the output from the Oracle database.

->./deref.ksh
echo deference
MYUSER 
mysupersecret
USER is "NDTC_DBA"

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s