Bourne Shell: How to concatenate variables that need to be evaluated?

蓝咒 提交于 2020-01-05 07:11:38

问题


I'm having trouble figuring out a way to properly concatenate several variables together. The idea is to collect several items over time (in this case "foo", "bar", and "baz") and then concatenate together into one string (ex: X = "foo bar baz").

The following is the code I have put together so far:

#!/bin/sh
N=0
# assign foo
eval "DATA${N}='foo'"
eval "echo First value is: \$DATA$N"   # First value is: foo
N=`expr $N + 1`

# assign bar
eval "DATA${N}='bar'"
eval "echo Next value is: \$DATA$N"    # Next value is: bar
N=`expr $N + 1`

# assign baz
eval "DATA${N}='baz'"
eval "echo Last value is: \$DATA$N"    # Last value is: baz

for i in 0 1 2
do
        # concatenate foo bar and baz into one variable
done

The comment in the for-loop is the area I'm having trouble right now. Any help would be much appreciated. Thanks!


回答1:


You just have to escape the $ operator for the first eval pass:

blob=
for i in 0 1 2
do
    eval blob="\$blob\$DATA${i}"
done


来源:https://stackoverflow.com/questions/3294864/bourne-shell-how-to-concatenate-variables-that-need-to-be-evaluated

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!