0

I am looking for a way to add a string to a variable name in bash and evaluate this as a new variable. Example:

#!/bin/bash
file="filename"
declare ${file}_info="about a file"
declare ${file}_status="status of file"
declare ${file}_number="29083451"

echo ${${file}_info}  # <-- This fails with error: "bad substitution"

Is there a way to do this?

I'm not actually implementing this in any production code anywhere. I just want to know if there is some way to create a variable name using a variable and a string. It seemed like an interesting problem.

Also note that I am not asking about bash indirection, which is the use of ${!x} to evaluate the contents of a variable as a variable.

4
  • It looks like the eval approach given in stackoverflow.com/questions/8435256/… might be the one you are looking for. Commented Oct 6, 2014 at 21:54
  • 1
    The indirection FAQ tells you how to write, not just how to read, so it actually is the same topic. Commented Oct 6, 2014 at 22:09
  • Agreed. As I have reviewed comments and answers, it would seem that indirection must be involved in the solution. I was hoping for another way, but it seems that there is at least one solution if indirection is used in the process. Commented Oct 6, 2014 at 22:10
  • 1
    @jpe, re: eval, see BashFAQ #48: mywiki.wooledge.org/BashFAQ/048 Commented Oct 6, 2014 at 22:29

1 Answer 1

0

You aren't asking about indirection, but that's what can help you:

info=$file\_info
echo ${!info}
Sign up to request clarification or add additional context in comments.

1 Comment

Apparently my edit was rejected. It seems that your answer should say ${!info} instead of ${!name}. I had also hoped to achieve this without using a placeholder variable like "info" that you are using here, but you have indeed solved the problem. Will accept your answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.