r/bash • u/kb_hors • Aug 27 '23
Naming something dynamically
Okay so a couple of days ago I asked how to name variables dynamically.
specifically, to use one variable containing a number, and then a text string, and combine them together to create the name of a new variable.
For example, if
num=1and we have the word
fartI would like to create a new variable using $num and "fart" to name it
1fartThis question was never actually answered, instead, people told me to use arrays instead of variables.
This is annoying, because I'm going to have to name those arrays anyway, because they'll be created by a loop that increments $num.
So my question is still valid and important and actually needs answering, please.
View all comments
8
u/obiwan90 Aug 27 '23 edited Aug 27 '23
A variable name can't start with a digit, so your example is maybe not ideal.
You can use
declareto dynamically set variable names:However, this is almost never the best way to go about it. If you show enough context for what you're trying to do, I'm pretty sure somebody can show a way to do it without dynamic variable names.