Home > Net >  Bash associative array has elements that are not defined in them
Bash associative array has elements that are not defined in them

Time:08-05

I have a bash command that receives an associative array from python:

string=$(/path/to/my-profiles.py --my-profiles setenv)
echo $string
>>> ( ['SOME_ENV']='1' )

declare -A env=string

for i in "${!env[@]}"
do
  echo "key  : $i"
  echo "value: ${env[$i]}"
done


>>>key  : SOME_ENV
value: 1
key  : 0
value: array

I didn't add key, value of 0 and array into the associative array. How to avoid this ?

CodePudding user response:

declare -A env=array

Assigns the string array to variable env. All variables are one element arrays with index zero. Because env is an array, the string gets assigned to the element with index 0.

Check variables values with declare -p env.

How to avoid this ?

Is unclear. To not assign to a key 0, actually assign an element with some value to the array.

declare -A env=( [something]=somethingelse )

CodePudding user response:

Assuming the content of the string variable looks like:

declare -- string="( [SOME_ENV]=1 )"

A small change to OP's declare -A statement:

declare -A env="${string}"

This gives us:

$ typeset -p env
declare -A env=([SOME_ENV]="1" )

$ for i in "${!env[@]}"; do   echo "key  : $i";   echo "value: ${env[$i]}"; done
key  : SOME_ENV
value: 1
  •  Tags:  
  • bash
  • Related