简体   繁体   中英

Increment variable number and assign new value

I'm trying to assign values from a list to a set of variables. The variable number start from 1 and keeps increasing according to the number of values in the list. I did a quick for loop, but I get errors.

list="010 110 004"
num=0
for node in `echo $list`
do
    ((num+=1))
    node_$num="my_host-$node.test.edu.com"
    echo $node_$num
done

But I get errors like this:

bash: node_1=my_host-010.test.edu.com: command not found
1
bash: node_2=my_host-110.test.edu.com: command not found
2
bash: node_3=my_host-004.test.edu.com: command not found
3

How can I assign values from the list to an increasing set of variables?

This is how you should have it in bash :

list=(010 110 004)
num=0

for node in "${list[@]}"; do
    ((num+=1))
    var="node_$num"

    # use declare to create and instanitate var=value
    declare "$var"="my_host-$node.test.edu.com"

    # examine value o f$var
    declare -p "$var"
    # or use this echo to print just value
    # echo "${!var}"
done

declare -- node_1="my_host-010.test.edu.com"
declare -- node_2="my_host-110.test.edu.com"
declare -- node_3="my_host-004.test.edu.com"

Also note use of shell arrays for safe iteration of a finite list of items.

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