1

I have array:

declare -A server
server[172.16.170.1]='t1.com'
server[172.16.170.2]='t2.com'
server[172.16.170.3]='t3.com'
server[172.16.170.4]='t4.com'
server[172.16.170.5]='t5.com'
.....

I don't want to write every time, "t1,com,t2.com ..." I want to increment it Ok:

first=0
first=$(($first+1))

It is work for the first element.

first=0
first=$(($first+1))
declare -A server
server[172.16.170.1]='t$first.com'
server[172.16.170.2]='t$first.com'
server[172.16.170.3]='t$first.com'
server[172.16.170.4]='t$first.com'
server[172.16.170.5]='t$first.com'
.....

In output we will have:

server[172.16.170.1]=t1.com
server[172.16.170.2]=t1.com
server[172.16.170.3]=t1.com
server[172.16.170.4]=t1.com
server[172.16.170.5]=t1.com
.....

I know, that we should use loop, but if i have a lot of servers, how i should use loop "for" ? With all my array variables ?

2 Answers 2

2

Couple of things missed out, use an arithmetic operator in bash as $((..)) with the pre-increment operator! under double-quotes

first=0
declare -A server
server[172.16.170.1]="t$((++first)).com"
server[172.16.170.2]="t$((++first)).com"
server[172.16.170.3]="t$((++first)).com"
server[172.16.170.4]="t$((++first)).com"
server[172.16.170.5]="t$((++first)).com"

and for printing the associative array just use the declare built-in.

declare -p server
declare -A server='([172.16.170.1]="t1.com" [172.16.170.3]="t3.com" [172.16.170.2]="t2.com" [172.16.170.5]="t5.com" [172.16.170.4]="t4.com" )'

And the for-loop version of the same. This will work ONLY in associative arrays (with declare -A array)

count=0
for i in "${!server[@]}"; do 
    server["${i}"]="t$((++count)).com"
done
Sign up to request clarification or add additional context in comments.

Comments

1

How about this:

declare -A server
for ((i=1; i<=5; i++))
do
  server[172.16.170.$i]=t$i.com
done

4 Comments

not bad. but if i don't know, how many elements in my array ?
You need to tell me where the information is originally. If you don't have it at all, we cannot do it. Is the array filled with the correct keys already? Then we can iterate over them and derive the values from them (at least it seems like this up to now). (I just see that's what Inian has implemented.)
I have a lot of values. I show you first five, and of course, we have different IP. not only 172.16.170.0/24, i have a 192.168.1.0/24 and others.
Yes, but where do you have it? In what data structure can the bash look them up?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.