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

3
  • But... what for? Commented Nov 12, 2020 at 12:29
  • Does this answer your question? Bash indirect variable reference Commented Nov 12, 2020 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. Commented Nov 12, 2020 at 14:04

1 Answer 1

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]++))
Sign up to request clarification or add additional context in comments.

3 Comments

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.
? 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.
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.

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.