The-Minh Kieu
The-Minh Kieu

Reputation: 1

Echo $variable$counter in a "for" loop BASH

n=1
test=1000
test1=aaa

I'm trying:

echo $test$n

to get

aaa

But I get

10001

I'm trying to use it that way because I have variables: lignePortTCP1,lignePortTCP2,lignePortTCP1, ETC in a for loop like this:

declare -i cpt3
cpt3=0
for ((i = 1; i <= cpt; i++)); do
    cpt3=cpt3+1
    echo "Port/Protocole : $lignePortTCP$cpt3 - Nom du Service : $ligneServiceTCP$cpt3"
done

Upvotes: 0

Views: 101

Answers (4)

Charles Duffy
Charles Duffy

Reputation: 295383

Given the assigned variables

n=1
test1=aaa

...and you want to print aaa given the values of test and n, then put the name you want to expand in its own variable, and expand that with the ! operator, like so:

varname="test$n"
echo "${!varname}"

This is explicitly discussed in BashFAQ #6.


That said, variable indirection is not a particularly good practice -- usually, you can do better using arrays, whether associative or otherwise.

For instance:

test=( aaa bbb ccc )
n=0
echo "${test[n]}"

...for values not starting at 0:

test=( [1]=aaa [2]=bbb [3]=ccc )
n=1
echo "${test[n]}"

Upvotes: 3

Mark Reed
Mark Reed

Reputation: 95252

One way would be to use ${!}, but you have to store the combined name in its own variable for that to work:

var=test$n
echo "${!var}"

If you have control over how the variables get assigned in the first place, it would be better to use an array. Instead of lignePortTCP1, lignePortTCP2, etc., you would assign the values to lignePortTCP[0], lignePortTCP[1], etc. and then retrieve them with ${lignePort[$n]}.

Upvotes: 0

Nick Russo
Nick Russo

Reputation: 1542

You could also use eval, though it's probably not better than the technique provided by Charles Duffy.

$ n=1
$ test=1000
$ test1=aaa
$ eval echo \${test$n}
aaa

Upvotes: 0

Nick Russo
Nick Russo

Reputation: 1542

If you want to subtract the values of test and n, wrap the computation in $(( ... )) and use the - operator:

$((test-n))

Upvotes: 0

Related Questions