Bash: Variable substitution in variable name with default value
- by krissi
i have the following variables:
# config file
MYVAR_DEFAULT=123
MYVAR_FOO=456
#MYVAR_BAR unset
# program
USER_INPUT=FOO
TARGET_VAR=<need to be set>
If the USER_INPUT is "foo", I want TARGET_VAR to be the value of MYVAR_FOO (TARGET_VAR=456). If USER_INPUT is "bar" I want TARGET_VAR to be set to MYVAR_DEFAULT (123), because MYVAR_BAR is unset.
I prefer it to be sh-compatible and as a substitution string. But it might also be bash compatible and/or in a function.
I got these snippets:
# Default values for variable (sh-compatible)
echo ${MYVAR_FOO-$MYVAR_DEFAULT}
# Uppercase (bash compatible)
echo ${USER_INPUT^^}
I would need something like this:
TARGET_VAR="${MYVAR_${USER_INPUT^^}-$MYVAR_DEFAULT}"
# or
somecommand -foo "${MYVAR_${USER_INPUT^^}-$MYVAR_DEFAULT}"
This is to switch a bunch of variables between multiple "profiles". In the example, FOO and BAR are profiles. New profiles should be added easily, in this example there would be an implicit profile named BAZ, too, all variables to their default values.
Unfortunately it is not that easy. Do you have an idea to solve this?
Thanks in advance,
krissi