Languages and Scripting
Showing results for 
Search instead for 
Do you mean 

Use content of variables to get content of variable

SOLVED
Go to Solution
Respected Contributor [Founder]

Use content of variables to get content of variable

I have a function which will accept two variables:
type
dest

Then I have a bunch of variable pre-define such as:
cku=1234567890@txt.domain

The content of "type" will be "c".
The content of "dest" will be "ku"

So I want to display teh content of varible "cku" by concatenating the contents of "type" and "dest".

I've tried
echo "${${type}${dest}}" and other forms to try and get the content of "cku" displayed.

I will use this in a more complicated script which is why I'm not simply doing
echo "${cku}"

Can I use the content of 2 variables to build the name of the third variable and then display the content of that 3rd variable?

Cheers
The Devil is in the detail.
7 REPLIES
Honored Contributor [Founder]

Re: Use content of variables to get content of variable

Use the "eval" command.
x=${type}${dest}
eval echo \$$x

HTH

-- Rod Hills
There be dragons...
Acclaimed Contributor [Founder]

Re: Use content of variables to get content of variable

Hi Kevin:

I don't believe that the shell provides this kind of substitution. One sure wishes that it did.

Regards!

...JRF...
Acclaimed Contributor [Founder]

Re: Use content of variables to get content of variable

Hi Rodney:

Why thanks :-))

/* No points for either of my posts, please! */

Regards!

...JRF...
Respected Contributor [Founder]

Re: Use content of variables to get content of variable

Thanks Rodney.
The eval works on it's own.

But how can I plug that into a command?

Example


mailx -s " some text " eval echo \$$x

Where it would result in
mailx -s "some text" 1234567890@txt.domain
The Devil is in the detail.
Respected Contributor [Founder]

Re: Use content of variables to get content of variable

Got it working.

Will post solution and assign points ASAP
The Devil is in the detail.
Respected Contributor [Founder]

Re: Use content of variables to get content of variable

This is a shortened version of my much longer script but has the basic logic and shows how the eval statement allows using 2 variables to get the content of a 3rd variable.

--- start of script
cku="1234567890@txt.cellprovider.com"
eku="ku@emailaddress.com"

escalate() {
# format
# escalate type destination_name message

nf_dest="${1}${2}"
nf_body="$3"

#Purposely not using subject line in mailx
echo "${3}" | eval mailx \$${nf_dest}

}

# Sample calls to function
escalate c ku "test message to cell"
escalate e ku "test message to email"

--- end of script
The Devil is in the detail.
Highlighted
Respected Contributor [Founder]

Re: Use content of variables to get content of variable

see above
The Devil is in the detail.