Dana Amilov
Dana Amilov

Reputation: 23

How to include parameter inside another parameter in bash

doing the following:

for i in {0..3};do
        echo "${Card_${i}}"
done

my point is to get the print of parameters named "Card_1" "Card_2" and Card_3

Upvotes: 0

Views: 143

Answers (2)

PesaThe
PesaThe

Reputation: 7509

You could use variable indirection. However, since you've mentioned that each card is an array itself, declare -n (requires bash 4.3 or newer) might be your best option:

card_1=(c1a c1b)
card_2=(c2a c2b)

for i in {1..2}; do
    declare -n arr=card_$i
    echo "${arr[0]}"
done

# output:
# c1a
# c2a

Upvotes: 1

Tom Fenech
Tom Fenech

Reputation: 74695

It's perfectly possible to dynamically create variable names using an expansion:

$ card_1=111
$ card_2=222
$ card_3=333
$ printf '%s\n' $card_{1..3}
111
222
333

Brace expansion happens before parameter expansion, so $card_{1..3} is expanded to $card_1 $card_2 $card_3 before the parameters are expanded.

That said, it looks like you're using numerical suffixes to emulate an array:

$ cards=( 111 222 333 444 )
$ printf '%s\n' "${cards[@]:0:3}"
111
222
333

I used a slice 0:3 just to show how they work.

Upvotes: 3

Related Questions