bash4 read file into associative array bash4 read file into associative array arrays arrays

bash4 read file into associative array


First thing, associative arrays are declared with -A not -a:

local -A ary

And if you want to declare a variable on global scope, use declare outside of a function:

declare -A ary

Or use -g if BASH_VERSION >= 4.2.

If your lines do have keyname=valueInfo, with readarray, you can process it like this:

readarray -t lines < "$fileName"for line in "${lines[@]}"; do   key=${line%%=*}   value=${line#*=}   ary[$key]=$value  ## Or simply ary[${line%%=*}]=${line#*=}done

Using a while read loop can also be an option:

while IFS= read -r line; do    ary[${line%%=*}]=${line#*=}done < "$fileName"

Or

while IFS== read -r key value; do    ary[$key]=$valuedone < "$fileName"