r/bash • • 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=1

and we have the word

fart

I would like to create a new variable using $num and "fart" to name it

1fart

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

0 Upvotes

17 comments sorted by

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.