Bourne Shell: How to concatenate variables that ne

2019-07-24 21:36发布

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!

标签: sh
1条回答
别忘想泡老子
2楼-- · 2019-07-24 22:04

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
查看更多
登录 后发表回答