V
V
Valeriu1472017-04-05 12:13:44
bash
Valeriu147, 2017-04-05 12:13:44

How to increment a value in a bash associative array?

Good afternoon. There is a small associative array with a large number of values ​​and keys. And so, there was an idea to simplify it by means of incrementation of values.
The array itself:

declare -A host
host[192.168.1.1]='test1.ru'
host[192.168.1.2]='test2.ru'
host[192.168.1.3]='test3.ru'
host[192.168.1.4]='test4.ru'
host[192.168.1.5]='test5.ru'

How to get out so as not to write the name of the site, every time.
I tried like this
first = 1
host[192.168.1.1]='test$first.ru'

But at the output I get
host[192.168.1.1]='test$first.ru'
Could you tell me what can be done in this situation. Thank you for your attention.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Stepan Krapivin, 2017-04-05
@Valeriu147

in a string, you need to escape the variable using curly braces

first=1
echo "test${first}.ru"

K
Kevin1, 2017-04-05
@Kevin1

You can simplify it a little more:
#! /bin/bash
declare -A host
for i in $(seq 1 5); do
eval host[192.168.1.$i]="test${i}.ru"
done
echo ${host[*]}
Output:
test4.ru test5.ru test1.ru test2.ru test3.ru

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question