Shell Tips - how to compose variable ?

If you want to use compose variable name, such as

#/bin/sh
i=1
x1=stringX1

echo "$x$i"

The result "1" is not what you want.  It just string "$x"+"xi".

In sh using eval  can help you handle compose variable name:

#/bin/sh
i=1
x1=stringX1

eval echo "\\$x$i"

The result is "stringX1", it echo variable $x1' value. 

For more information about eval ,please see man page.

 

Here has some example of eval:

1.Set variable value by variable name condition

v1=aaa
v2=bbb
c=1
if [ $c -eq 1 ]
then
vname=v$c #find variable name by condition.
eval vvv="$"$vname ; echo vvv: $vvv #set v1 value to vvv, vvv=aaa
eval vvv='$'$vname ; echo vvv: $vvv #
set v1 value to vvv, vvv=aaa
#eval vvv=$$vname ; echo vvv: $vvv  #error usage
fi

2. v1' value "aaa" as a variable name, and set value for variable "aaa"

v1=aaa ; vaaa="This is aaa"
#eval $v1=$vaaa ; echo aaa: $aaa #error
#eval $v1="$vaaa" ; echo aaa: $aaa #error
eval $v1='$vaaa' ; echo aaa: $aaa


 

3.v1' value "aaa" as a variable name, and set variable name as value

v1=aaa ; vaaa="This is aaa"
eval $v1=$v1 ; echo aaa: $aaa
eval $v1="$v1" ; echo aaa: $aaa
#There is space in vaaa'value
eval $v1='$v1' ; echo aaa: $aaa

 

In Ksh who know how to use eval?  


 

Comments:

I don't understand your question about KSH eval.

Posted by Nico on July 09, 2007 at 06:24 PM CST #

Firstly, thanks for relay :). I just want to somebody can give me a simple example in KSH which have same function with : #/bin/sh i=1; x1=stringX1; echo "$x$i"

Posted by xue on July 10, 2007 at 06:58 AM CST #

The same exact thing works in KSH.

Posted by Nico on July 10, 2007 at 09:55 PM CST #

Thanks for reply.

Posted by xue on July 11, 2007 at 02:58 AM CST #

Erm, technicially the use of "eval" should be avoided since it may allow script users to "inject" code that way.

At least ksh93 has a way to do the same using the "nameref" datatype ("name reference", it works like a filesystem softlink for variables), for example:

$ foo="bar"
$ nameref x=${foo}baz
$ barbaz="hello"
$ print $x
hello
See the termclock demo from the ksh93-integration project for shell code which uses nameref's to access variables which are passed via name as function arguments.

Posted by Roland Mainz on July 22, 2007 at 04:27 AM CST #

Post a Comment:
Comments are closed for this entry.
About

williamxue

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today