2

I have the following associative array.

var1="dog"
var2="cat"
var3="moose"

declare -A asar01=(
["one"]="$var1"
["two"]="$var2"
["three"]="$var3"
)

I want to loop through and print each values variable name. So only "var1", "var2" and "var3" will print. How can I accomplish this? I tried the following but it prints the actual scripts name. as the first variable output.

for i in "${!asar01[@]}";do
    echo "${!asar01[$i]}"
done

My example is trying to use the ${!variable} method to print the name but its not working. How can I accomplish this?

1 Answer 1

4

You are trying to use indirect expansion backwards. If you want to retain the variable name drop the $ from your associative array assignments

#!/bin/bash

var1="dog"
var2="cat"
var3="moose"

declare -A asar01=(
["one"]="var1"
["two"]="var2"
["three"]="var3"
)

for i in "${!asar01[@]}"; do
   printf 'Key is: %s\n' "$i"
   printf 'Var name is: %s\n' "${asar01[$i]}"
   printf 'Var value is: %s\n' "${!asar01[$i]}"
done
2
  • Interesting, I did not know I could do that. Thank you!
    – Dave
    Apr 7, 2022 at 19:53
  • I should mention, after further testing, putting integers in the key location of the associative array caused problems. (So changing "one" "two" and "three" to integers). If there was overlap the index was not parsed by bash. All good, if the integer is the value then this problem does not happen.
    – Dave
    Apr 7, 2022 at 20:23

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .