1

I'm trying to find all variables which match a particular pattern and print their values.

test_a="apple"
test_b="banana"
test_c="carrot"
test_d="doughnut"

test_show_all () {
    local i
    for i in ${!test_*}; do
        printf "..$i\n"
    #   printf "..$i-->${$i}\n"
    done    
}

The loop is finding the correct variables. But if I uncomment the second line of the for loop, bash is unhappy with the syntax ${$i}. I thought this should work since $i holds the name of a variable, so I thought ${$i} should expand to value of that stored name.

0

2 Answers 2

5

The indirect variable reference is ${!var}. Change your code to

printf "..$i-->${!i}\n"

and it should work.

Sign up to request clarification or add additional context in comments.

1 Comment

1

Not useful now, but in bash 4.3, you will also be able to use namerefs.

for name in ${!test_*}; do
  declare -n value=$name
  printf "..$name->$value\n"
done

As a short cut, if you only want to iterate over the values (without regard to the actual name of the variable), you can use

declare -n value
for value in ${!test_*}; do
  printf "..$value\n"
done

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.