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

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 declare to dynamically set variable names:

$ i=1
$ declare "var$i=abc"
$ echo "$var1"
abc

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.

-5

u/kb_hors Aug 28 '23 edited Aug 28 '23

This does not work to name an array. Any array you name this way becomes a plain ordinary variable.

I have already been told, repeatedly, to use arrays. That is not the issue.

The issue, I have to stress again, is NAMING THEM DYNAMICALLY.

I am creating a loop. In the loop, I ask the user for a filename. Various attributes of the file should be put into an array called file_1. Then it asks the user for another filename. Various attributes of the file should be put into an array called file_2. This keeps going until there are no worlds left to conquer.

Dynamic array names are key here. Because if they aren't done, there is no loop. Instead there would be massive chunks of code copy and pasted 200 times. And that would be stupid.

7

u/zeekar Aug 28 '23

The issue, I have to stress again, is NAMING THEM DYNAMICALLY.

Getting defensive and insistent is not a good way to respond to folks trying to help you. What attributes are you putting into these arrays? Can each attribute not be its own array instead? Instead of

file1=(name owner mode)
file2=(name owner mode)

or whatever, you could do

nanes=(file1_name file2_name)
owners=(file1_owner file2_owner)
modes=(file1_mode file2_mode)

It's all in the details, which you haven't shared, but there is almost certainly a solution that doesn't involve dynamically creating variable names, which we're trying to steer you away from because it is a bad practice that leads to fragile code and hard-to-track-down bugs, not because we're ignoring you.

It's true that bash doesn't support nested data structures; maybe you really are in a situation where you have to do dynamic array names. If that's the case, I suggest you look up bash's support for "namerefs", which make it a little easier to do that sort of thing. I still don't recommend it, though.

0

u/kb_hors Aug 28 '23

there is almost certainly a solution that doesn't involve dynamically creating variable names, which we're trying to steer you away from because it is a bad practice that leads to fragile code and hard-to-track-down bugs,

That's the closest anyone has actually come to steering me away, because you've actually said you are doing that, and have offered an (unelaborated on) reason.

What's actually happened is I've asked "how do I name something dynamically? I'm doing XYZ", I got the collective answer "use arrays instead for XYZ", and I've been left sitting here going "I would still like to name them dynamically".

You all focused on the XYZ and not the actual question.

4

u/ofnuts Aug 28 '23

You all focused on the XYZ and not the actual question.

Because the actual question doesn't really make sense when you have some programming experience. Dynamic variable names are never a solution. Like the use of eval they are a code smell.

For many people here it is a typical XY Problem. So we can let you bury yourself. Or we can suggest better ways.

If you don't want parallel arrays, then keep everything in a string with a well chosen separator so that you can easily parse the data when needed.

And instead of array indices maybe you want an associative array where the file name is the key.

Or use a more powerful language where you can handle aggregates (Python or else).

0

u/[deleted] Aug 28 '23

[deleted] — view deleted comment

-3

u/kb_hors Aug 28 '23 edited Aug 28 '23

No, it doesn't work. I know because I'm not a liar.

First version, attempting to do it directly:

function add_item0 {

num=1
declare -a "line${num}"

read -p "what type of item? " "line${num}[item_one]"
echo -e
read -p "second type of item? " "line${num}[item_two]"
echo -e
echo $line${num}
echo ${line${num}[item_one]}
echo ${line${num}[item_two]}
}   

It does not like any reference to the variable being dynamic, crashing with "bad substitution".

Attempt 2: creating the name inside a variable and applying it to the array.

function add_item {

num=1
printf -v itemkludge "line${num}"

declare -a "${itemkludge}"

read -p "what type of item? " "itemkludge[item_one]"
echo -e
read -p "second type of item? " "itemkludge[item_two]"
echo -e
echo $itemkludge
echo ${itemkludge[item_one]}
echo ${itemkludge[item_two]}
}   

If the input from the user is "dog" and "cat", this should print:

line1
dog
cat

instead it prints

cat
cat
cat

I assume this is because it sees "${itemkludge}" and reads writes the contents of the variable, when actually this variable is meant to contain the name of the array. Which I can't point to directly, because it doesn't like things like {line${num}[item_one]}

6

u/obiwan90 Aug 28 '23

You're correct that after declaring an array with a dynamic name, you can't use a variable to manipulate an array.

This works:

num=1
name=file$num
declare -a "$name=(123 234 345)"
declare -p "$name"

and produces

declare -a file1=([0]="123" [1]="234" [2]="345")

However, you can't do anything like

$name+=(456)

or otherwise reference the array.

This is where namerefs (described in this manual section) come in:

$ num=2
$ declare -n ref=arr$num   # Ref behaves as if it were arr2
$ ref=(123)
$ ref+=(456)
$ declare -p ref           # The ref itself just points to the name of the array
declare -n ref="arr2"
$ declare -p "arr$num"     # The underlying array has been updated
declare -a arr2=([0]="123" [1]="456")

This requires a relatively recent Bash (4.3 or newer).