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?
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?
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]}"