bash 在unix中用echo打印两个没有空格的变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17021153/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 05:38:55  来源:igfitidea点击:

Print two variables without space with echo in unix

bashunixecho

提问by Piyush Baijal

VAR1=ABC;
VAR2=XYZ;
VAR3=PQR;

I want to print value of VAR1,VAR2 and VAR3 in a for loop. Please help!

我想在 for 循环中打印 VAR1、VAR2 和 VAR3 的值。请帮忙!

In a for loopi am trying to do echo $VAR$i

for loop我试图做的echo $VAR$i

Expected O/P:

预期 O/P:

ABC
XYZ
PQR

Actual Output:

实际输出:

1
2
3

回答by choroba

Use an array:

使用数组:

VAR[1]=ABC
VAR[2]=XYZ
VAR[3]=PQR
for i in 1 2 3 ; do
    echo ${VAR[i]}
done

Or, use the variable indirection:

或者,使用变量间接:

VAR1=ABC
VAR2=XYZ
VAR3=PQR
for i in 1 2 3 ; do
    name=VAR$i
    echo ${!name}
done

回答by fedorqui 'SO stop harming'

You can do it like this:

你可以这样做:

for i in 1 2 3
do
   eval "echo $VAR${i}"
done

The key point is the evalcommand.

关键是eval命令。

Test

测试

$ VAR1=ABC; VAR2=XYZ; VAR3=PQR;
$ for i in 1 2 3; do eval "echo $VAR${i}"; done
ABC
XYZ
PQR

回答by Alfishe

echo "${VAR1}${VAR2}${VAR3}"

Simple as that. I don't think it make sense to create useless cycles just to concatenate several values into a string

就那么简单。我认为仅仅为了将几个值连接成一个字符串而创建无用的循环是没有意义的

回答by tusharmakkar08

Instead of

代替

echo $VAR$i
在 for 循环中做

varx=$varx$var$i

and initialize varx as empty string and at end do

并将 varx 初始化为空字符串,最后做

echo $varx

This is for printing without space as the question suggests.

正如问题所暗示的那样,这是用于没有空间的打印。