0

I have 2 variables in bash which are:

$SECRETS_ARN_LIST .. which is:

arn:aws:secretsmanager:us-east-1:12234:secret:/test/app/A
arn:aws:secretsmanager:us-east-1:12234:secret:/test/app/B
arn:aws:secretsmanager:us-east-1:12234:secret:/test/app/C
arn:aws:secretsmanager:us-east-1:12234:secret:/test/app/B

$SECRETS_ARN_LIST_NAMES ... which is :

/test/app/A
/test/app/B
/test/app/C
/test/app/D

Now, what I want to do is to put them in an array like a key value par. Something like:

key : value

where key would be the "/test/app/A" and value would be "arn:aws:secretsmanager:us-east-1:12234:secret:/test/app/A"

How would I do that in a bash script?

mgb
  • 555
  • 1
  • 7
  • 23

1 Answers1

1

Given

SECRETS_ARN_LIST=$(cat <<END
arn:aws:secretsmanager:us-east-1:12234:secret:/test/app/A
arn:aws:secretsmanager:us-east-1:12234:secret:/test/app/B
arn:aws:secretsmanager:us-east-1:12234:secret:/test/app/C
arn:aws:secretsmanager:us-east-1:12234:secret:/test/app/B
END
)

SECRETS_ARN_LIST_NAMES=$(cat <<END
/test/app/A
/test/app/B
/test/app/C
/test/app/D
END
)

Then

declare -A map
while read -r key value; do map[$key]=$value; done < <(
  paste <(echo "$SECRETS_ARN_LIST_NAMES") <(echo "$SECRETS_ARN_LIST")
)

Now:

$ declare -p map
declare -A map=([/test/app/D]="arn:aws:secretsmanager:us-east-1:12234:secret:/test/app/B" [/test/app/A]="arn:aws:secretsmanager:us-east-1:12234:secret:/test/app/A" [/test/app/C]="arn:aws:secretsmanager:us-east-1:12234:secret:/test/app/C" [/test/app/B]="arn:aws:secretsmanager:us-east-1:12234:secret:/test/app/B" )

and

$ for key in "${!map[@]}"; do printf '%s => %s\n' "$key" "${map[$key]}"; done
/test/app/D => arn:aws:secretsmanager:us-east-1:12234:secret:/test/app/B
/test/app/A => arn:aws:secretsmanager:us-east-1:12234:secret:/test/app/A
/test/app/C => arn:aws:secretsmanager:us-east-1:12234:secret:/test/app/C
/test/app/B => arn:aws:secretsmanager:us-east-1:12234:secret:/test/app/B

Alternately, create two numerically indexed arrays:

readarray -t keys   < <(echo "$SECRETS_ARN_LIST_NAMES")
readarray -t values < <(echo "$SECRETS_ARN_LIST")

or take advantage of word splitting

# turn off glob expansion
set -f

# leave the variables _unquoted_
keys=( $SECRETS_ARN_LIST_NAMES )
values=( $SECRETS_ARN_LIST )

Then

for idx in "${!keys[@]}"; do
  printf '%s => %s\n' "${keys[idx]}" "${values[idx]}"
done

One advantage here is that the order is preserved.

glenn jackman
  • 223,850
  • 36
  • 205
  • 328