Reputation: 337
I have two env variables
SMTP_PASSWORD=SMTP_PASSWORD_KEY
MICROSCANNER_TOKEN=MICROSCANNER_TOKEN_KEY
I need to add this to a dict using bash
eg: arr["SMTP_PASSWORD"]=SMTP_PASSWORD_KEY
the key and value should be taken from env
Upvotes: 0
Views: 3035
Reputation: 12581
Outside your script:
export SMTP_PASSWORD=mySMTPKey
export MICROSCANNER_TOKEN=myMicroscannerKey
Inside your script:
As individual variables:
#!/bin/bash
SMTP_PASSWORD=${SMTP_PASSWORD_KEY}
MICROSCANNER_TOKEN=${MICROSCANNER_TOKEN_KEY}
As a map (available in Bash 4):
#!/bin/bash
declare -A MYMAP
MYMAP[SMTP_PASSWORD]=${SMTP_PASSWORD_KEY}
MYMAP[MICROSCANNER_TOKEN]=${MICROSCANNER_TOKEN_KEY}
To iterate over the external ENV and add key/value pairs:
#!/bin/bash
declare -A MYMAP
while IFS='=' read -r -d '' n v; do
MYMAP[${n}]=${v}
done < <(env -0)
# display all variable key value pairs
for K in "${!MYMAP[@]}"; do
echo $K = ${MYMAP[$K]};
done
Given your last comment, not wanting to bring in all ENV vars, you could do something like:
#!/bin/bash
envArray=( SMTP_PASSWORD MICROSCANNER_TOKEN )
declare -A MYMAP
for k in "${envArray[@]}"; do
MYMAP[$k]=${!k}
done
for K in "${!MYMAP[@]}"; do
echo $K = ${MYMAP[$K]};
done
Upvotes: 3
Reputation: 531185
You need an associative array (supported in bash
4 or later).
declare -A arr
arr[SMTP_PASSWORD]=$SMTP_PASSWORD
arr[MICROSCANNER_TOKEN]=$MICROSCANNER_TOKEN
There is no preexisting associative array that automatically includes all existing environment variables as its keys.
Upvotes: 0