Skip to content
Advertisement

Get variable name while iterating over array in bash

What I have is an array with some variables. I can iterate to get the values of those vars but what I need is actually their names (values will be used elsewhere).

Going with var[i] won’t work cause I will have different names. I guess I could workaround this by creating another array with the names – something similar to this: Getting variable values from variable names listed in array in Bash

But I’m wondering if there is a better way to do this.

JavaScript

Is:

JavaScript

Should be:

JavaScript

Advertisement

Answer

It sounds like you want an associative array.

JavaScript

This can also be assigned at once:

JavaScript

Either way, one can iterate over the keys with "${!Array[@]}", and retrieve the value for a key with ${Array[key]}:

JavaScript

…will, after either of the assignments up top, properly emit:

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement