Skip to content
Advertisement

BASH – Create arrays from lines of csv file, where first entry is array name

I’m learning to script in Bash. I have an CSV file, which contains next lines:

JavaScript

Need to create arrays from this, where first entry is array name, eg.

JavaScript

Here is my script:

JavaScript

When I try with csv file, containing only two first string (numbers and colors), code works well. And if i try to with number, colors, custom-1, custom-2, there is error during reading csv:

JavaScript

because bash does not allow special characters in variable names, as far as I understand. Is there any way to avoid this?

Advertisement

Answer

As you cannot use the first column of your CSV file as bash array names one option would be to generate valid names using a counter (e.g. arrayN). If you want to access your data using the values of this first column you would also need to store them somewhere with the corresponding counter value. An associative array (declare -A names=()) would be perfect. Last but not least, the namerefs (declare -n arr=..., available starting with bash 4.3) will be convenient to store and access your data. Example:

JavaScript

Now, to access the values corresponding to, let’s say, entry custom+2, first get the corresponding counter value, declare a nameref pointing to the corresponding array and voilà:

JavaScript

Let’s declare a function for easier access:

JavaScript

And then:

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