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?  

 

5 thoughts on “Shell Tips – how to compose variable ?

  1. 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”

  2. 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.

发表评论

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 / 更改 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s