Home > database >  Bash : Split Array into KV pairs
Bash : Split Array into KV pairs

Time:05-17

I am working on a script, where via JQ I am getting Environment variables and I need them in KV pairs for other type of file. Currently, i have the elements as follows in a Bash array

DD_TRACE_CLI_ENABLED:true
PRODUCT:buy_box
TRACE_ID:$NOMAD_ALLOC_ID

Now, When I am printing, I need it like this:

- name: DD_TRACE_CLI_ENABLED
  value: true
- name: PRODUCT
  value: buy_box

My current code

if [ ! -z "$env_params" -a "$env_params" != " " ]; then
env_params_as_array=(${env_params//,/ })
for each in "${env_params_as_array[@]}"
do
echo $each
echo -e "${myCustomIndentTab}- $each" >> values-$1.yaml
done
fi

How can I achieve that? Thank you.

CodePudding user response:

bash array:

env_params_as_array=(
    DD_TRACE_CLI_ENABLED:true
    PRODUCT:buy_box
    TRACE_ID:$NOMAD_ALLOC_ID
)

printing it the way you want:

for p in "${env_params_as_array[@]}"
do
    IFS=':' read -r k v <<< "$p"
    printf -- '- name: %s\n  value: %s\n' "$k" "$v"
done |
sed "s/^/$myCustomIndentTab/" > "values-$1.yaml"
  • Related