2
INPUT=10     
OUTPUT_IN=20     
KEYWORD="IN"    
echo $OUTPUT_"$KEYWORD"   

It should display 20

Mainly I am looking to generate the variable name OUTPUT_IN

How to resolve this?

2
  • How do I resolve this? Commented Jul 7, 2010 at 13:15
  • like this : eval newvar=\$$varname Commented Jul 7, 2010 at 13:18

2 Answers 2

4

You can use indirection in Bash like this:

INPUT=10     
OUTPUT_IN=20     
KEYWORD="IN"    
var="OUTPUT_$KEYWORD"
echo "${!var}"

However, you should probably use an array or some other method to do what you want. From BashFAQ/006:

Putting variable names or any other bash syntax inside parameters is generally a bad idea. It violates the separation between code and data; and as such brings you on a slippery slope toward bugs, security issues etc. Even when you know you "got it right", because you "know and understand exactly what you're doing", bugs happen to all of us and it pays to respect separation practices to minimize the extent of damage they can have.

Aside from that, it also makes your code non-obvious and non-transparent.

Normally, in bash scripting, you won't need indirect references at all. Generally, people look at this for a solution when they don't understand or know about Bash Arrays or haven't fully considered other Bash features such as functions.

And you should avoid using eval if at all possible. From BashFAQ/048:

If the variable contains a shell command, the shell might run that command, whether you wanted it to or not. This can lead to unexpected results, especially when variables can be read from untrusted sources (like users or user-created files).

Bash 4 has associative arrays which would allow you to do this:

array[in]=10
array[out]=20
index="out"
echo "${array[$index]}"
Sign up to request clarification or add additional context in comments.

Comments

3
eval newvar=\$$varname

Source: Advanced Bash-Scripting Guide, Indirect References

Comments

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.