Go Back   The UNIX and Linux Forums > Top Forums > Shell Programming and Scripting


Shell Programming and Scripting Post questions about KSH, CSH, SH, BASH, PERL, PHP, SED, AWK and OTHER shell scripts and shell scripting languages here.

Reply    
 
Thread Tools Search this Thread Display Modes
    #1  
Old 03-16-2013
Registered User
 
Join Date: Sep 2009
Posts: 139
Thanks: 95
Thanked 6 Times in 5 Posts
How to set a variable name from another variables value?

Experts,

I want to set value of variables like this in bash shell:

i=5 ; L=100

I want variable d5 (that is d(i) ) to be assign the value of $L ,


Code:
d$i=$L ;  echo $d5

Not working


Thanks.,
Sponsored Links
    #2  
Old 03-16-2013
Yoda's Avatar
Jedi Master
 
Join Date: Jan 2012
Location: Galactic Empire
Posts: 2,296
Thanks: 153
Thanked 733 Times in 705 Posts
You can use eval in this scenario:

Code:
eval d$i=$L ;  echo $d5

But I recommend to stay away from eval because using it is a security risk.

Array is the best choice for you here:

Code:
d[$i]=$L ;  echo ${d[$i]}

The Following User Says Thank You to Yoda For This Useful Post:
rveri (03-16-2013)
Sponsored Links
    #3  
Old 03-16-2013
Registered User
 
Join Date: Jul 2012
Location: San Jose, CA
Posts: 1,476
Thanks: 62
Thanked 532 Times in 465 Posts
As long as your script controls setting $i and $L (not letting a malicious user provide input that could cause $i or $L to expand to something like

Code:
$(do something)

that could destroy any data accessible by your script), the following should do what you want:

Code:
i=5;L=100
eval d$i=$L
echo $d5

The Following User Says Thank You to Don Cragun For This Useful Post:
rveri (03-16-2013)
    #4  
Old 03-16-2013
Registered User
 
Join Date: Sep 2009
Posts: 139
Thanks: 95
Thanked 6 Times in 5 Posts
Yoda, Thanks a lot it worked perfectly Don thanks a lot , it worked too and thanks for explaining that the variable could expand with wrong entries & could cause $i or $L to expand .
Sponsored Links
Reply

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

More UNIX and Linux Forum Topics You Might Find Helpful
Thread Thread Starter Forum Replies Last Post
Need to SET Environment variables shyamu544 Shell Programming and Scripting 1 07-01-2011 02:20 AM
What is the use of command set -- and set - variable? gomathi HP-UX 4 01-11-2011 12:19 PM
How to set permanent variables agasamapetilon AIX 7 09-01-2008 12:40 AM
Export command giving Variable Name vs the Value set for the Variable ParNone UNIX for Dummies Questions & Answers 2 04-03-2006 11:43 AM
Using Variables to Set Other Variables superdelic UNIX for Dummies Questions & Answers 3 04-21-2005 10:44 AM



All times are GMT -4. The time now is 10:23 PM.