0

I would like to read a config file and write it into a array. Everything before the = character should be the key for the array. Unfortunately, the bash does not interpret the variable correctly.

Unfortunately, it takes the variable name one to one.

ary["$key"]='test01 test02 test03'

The test config example:

IMAGES=test01 test02 test03
NEUIMAGE=test1 test2 test3

The script:

#!/bin/bash

FILENAME='/testfile'

readarray -t lines < "$FILENAME"

set -x

while IFS== read -r key value; do
    echo $key
    test=ary["$key"]=$value
    ary["$key"]=$value
done < "$FILENAME"

echo ${ary[@]}

The debugging output:

+ IFS==
+ read -r key value
+ echo IMAGES
IMAGES
+ test='ary[IMAGES]=test01 test02 test03‚
+ ary["$key"]='test01 test02 test03'
+ IFS==
+ read -r key value
+ echo NEUIMAGE
NEUIMAGE
+ test='ary[NEUIMAGE]=test1 test2 test3'
+ ary["$key"]='test1 test3 test2'
+ IFS==
+ read -r key value
+ echo test1 test3 test2
test1 test3 test2

What do I have to do to interpret the variable? Is there a better solution?

EDIT:

Thanks to @gniourf_gniourf !

Problem solved:

#!/bin/bash

FILENAME='/testfile'

set -x

declare -A ary

while IFS== read -r key value; do
    echo $key
    test=ary["$key"]=$value
    ary["$key"]=$value
done < "$FILENAME"

echo ${ary[@]}

Is there a more elegant way? Or is this already a good variant?

donnie
  • 23
  • 1
  • 7
  • You need to declare `ary` as an associative array. Before the loop, add this line: `declare -A ary`. Then, to visualize the associative array, use (at the end of the loop): `declare -p ary`. The `-A` option of `declare` is to declare the variable as associative array, and the `-p` option of `declare` is to display the value of the variable. `help declare` for more info on this builtin. – gniourf_gniourf Nov 23 '17 at 12:37
  • aside from the useless variables `lines` and `test`, it looks like what I'd write. `declare -p ary` is a good way to examine the contents of an associative array, or `for key in "${!ary[@]}"; do printf "%q => %q\n" "$key" "${ary[$key]}"; done` – glenn jackman Nov 23 '17 at 14:29
  • Possible duplicate of [bash4 read file into associative array](https://stackoverflow.com/questions/25251353/bash4-read-file-into-associative-array) – Léa Gris Sep 18 '19 at 14:28

0 Answers0