0

I want to use a variable within a variable name and can't figure out how to do it. Here's what I intend to do

if [some condition]; then
    id="A"
else
    id="B"
fi

${id}_count=$((${id}_count + 1))

Where, if the condition is met it would be

A_count=$(A_count + 1))

or if the condition is not met

B_count=$(B_count + 1))

The ${id} is obviously not working. I just tried it this way because it works this way in strings.

(No, it's not the only line I want to use $id in. Otherwise I would put it in the if-condition directly.)

How would it work within a variable name?

Thanks, Patrick

Patrick
  • 65
  • 5
  • But... what for? – KamilCuk Nov 12 '20 at 12:29
  • Does this answer your question? [Bash indirect variable reference](https://stackoverflow.com/questions/32418185/bash-indirect-variable-reference) – user1934428 Nov 12 '20 at 13:43
  • @user1934428 Somewhat, yes. But as I need to use $id in some other variables as well it doesn't clean up the code a lot as I still need to define a lot of different temporary variables as well. Still it's better than needing to use two variants of each variable. – Patrick Nov 12 '20 at 14:04

1 Answers1

0

Do not use eval. You may not follow this advise, and do:

if some condition; then
    id="A"
else
    id="B"
fi

eval "${id}_count=\$((${id}_count + 1))"
# or simpler:
# eval "((${id}_count++))"

But it's simpler to use an associative array (or a normal array):

declare -A count
if some condition; then
    id="A"
else
    id="B"
fi
((count[$id]++))
KamilCuk
  • 120,984
  • 8
  • 59
  • 111
  • Thanks, that works in general but as you said, rather don't use eval. I was hoping to work around arrays so that I don't have to rewrite the whole code. But if there is no other solution, that might be the only choice. – Patrick Nov 12 '20 at 14:05
  • ? I do not understand, I literally written an example below with an associative array. There's no sense in creating names of variables that depend on other variables content in bash - to use them, you would have to use `eval` anyway. That's the wrong approach to store and represent any data - the suggestion is here to remodel your problem (as this is most probably a XY question) and use a different data structure to represent your data. – KamilCuk Nov 12 '20 at 14:24
  • I understand that using arrays is probably the right way to do it. But this question corresponds to an existing code where so far I only needed one variable (A) but now I need two versions of every variable (A and B). With adding a variable within a variable name I was hoping to be able to change the whole (existing) code with little work. Changing the code for arrays is a lot more work and frankly I have very little experience with arrays. Again: Your answer is correct, I just hoped for a different, easier "fix" for my existing code. – Patrick Nov 12 '20 at 14:51