简体   繁体   中英

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 i in 1 2
do
echo $"CONNECT_ERETAIL""$i"
echo $"ERETAIL_DB""$i"
done

The expected output is:-

-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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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