0

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

4
  • for example if Card_1=222 the function will print 222 Commented Jul 17, 2018 at 10:44
  • Use arrays. Card=(1 2 3); for i in {0...3}; do echo ${Card[$i]}; done. If not, you need to use eval. eval echo "\"\${Card_$i}\"". Eval is bad. Commented Jul 17, 2018 at 10:48
  • each card is an array anyway so i'm not sure it will work Commented Jul 17, 2018 at 10:50
  • Take a look to this old answer of mine: stackoverflow.com/questions/51083594/… Commented Jul 17, 2018 at 10:50

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

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.