Bourne Shell:如何连接需要评估的变量? [英] Bourne Shell: How to concatenate variables that need to be evaluated?

查看:46
本文介绍了Bourne Shell:如何连接需要评估的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法找到将多个变量正确连接在一起的方法.这个想法是随着时间的推移收集几个项目(在这种情况下是foo"、bar"和baz"),然后将它们连接成一个字符串(例如:X =foo bar baz").

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

for 循环中的注释是我现在遇到问题的区域.任何帮助将非常感激.谢谢!

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

推荐答案

您只需要在第一次 eval 传递时转义 $ 运算符:

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

这篇关于Bourne Shell:如何连接需要评估的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆