Home > front end >  export an array with dynamic array name
export an array with dynamic array name

Time:03-14

For suppose there is a code

comp="LP"
n_names="abc456.com,def123.com,wxy098.com"
IFS=',' read -r -a n_split_list <<< "$n_names"

Now I want to export the n_split_list array with the following variable format. Remember comp need not always be "LP" . It changes based on argument given to the script.

export "$comp"_list="${n_split_list[@]}"

but the problem is coming while exporting ( only first item of the array is getting exported ) Please help!

CodePudding user response:

Assuming your values may contain whitespaces, you may use read again with dynamic variable name and comma as IFS:

comp="LP"
n_names="abc456.com,def123.com,w xy098.com"
IFS=',' read -r -a n_split_list <<< "$n_names"

IFS=, read -ra ${comp}_list < <(printf '%s,' "${n_split_list[@]}")

# check content of new array
declare -p ${comp}_list

declare -a LP_list=([0]="abc456.com" [1]="def123.com" [2]="w xy098.com")

Working Demo

  • Related