Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to construct variable name in Bash?

I want to construct variable name N_foo and N_bar and use their values in the following:

#!/bin/bash
N_foo=2
N_bar=3
for i in { "foo" "bar" }
do
    for j in { 1..$(`N_$i`) }
    do
        echo $j
    done
done

I want to use the values of N_foo and N_bar in the two inner loops and print out 1, 2 and 1, 2, 3, respectively. What's the correct syntax?

like image 334
Meng Lu Avatar asked Dec 05 '22 21:12

Meng Lu


2 Answers

#!/bin/bash
N_foo=2
N_bar=3
for i in "foo" "bar"
do
    key="N_${i}"
    eval count='$'$key
    for j in `seq 1 $count`
    do
        echo $j
    done
done
like image 104
Ravi Avatar answered Jan 01 '23 06:01

Ravi


You can use the indirect variable reference operator:

Example

var="foo"
nfoo=1
ref=n${var}
echo $ref
echo ${!ref}

Which gives this output:

nfoo
1
like image 29
sashang Avatar answered Jan 01 '23 06:01

sashang