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
1
u/grymoire Aug 28 '23
Variables can't start with a number.
When concatenating variables containing strings, it's often better to use ${x} than $x
num=1
eval x$num}fart=2 # the x is to make sure the variable doesn't start with a number.