简体   繁体   English

如何在 Bash 脚本中引用循环内的变量值以及递增的变量名

[英]How to refer variable value inside for loop along with incrementing variable name in Bash scripting

We have below variables declared as such我们有以下声明的变量

CONNECT_ERETAIL1="-h17.XXX.XXX.XX1 -uroot -pXXXXXX"
CONNECT_ERETAIL2="-h17.XXX.XXX.XX2 -uroot -pXXXXXX"

ERETAIL_DB1=/usr01/eretail_db1.txt
ERETAIL_DB2=/usr01/eretail_db2.txt

We need to refer them inside for loop我们需要在 for 循环中引用它们

for i in 1 2
do
echo $"CONNECT_ERETAIL""$i"
echo $"ERETAIL_DB""$i"
done

The expected output is:-预期的 output 是:-

-h17.XXX.XXX.XX1 -uroot -pXXXXXX
/usr01/eretail_db1.txt
-h17.XXX.XXX.XX2 -uroot -pXXXXXX
/usr01/eretail_db2.txt

How to achieve this?如何做到这一点?

This is what you are looking after:这就是您所关注的:

for i in 1 2; do
    t1="CONNECT_ERETAIL$i"
    t2="ERETAIL_DB$i"
    echo "${!t1}"
    echo "${!t2}"
done

You can read more about that kind of parameter expansion in this manual .您可以在本手册中阅读有关这种参数扩展的更多信息。

Also, using all-uppercase variables is discouraged as they may conflict with bash environment variables.此外,不鼓励使用全大写变量,因为它们可能与 bash 环境变量冲突。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM