Bash: Variable substitution in variable name with default value

Posted by krissi on Server Fault See other posts from Server Fault or by krissi
Published on 2012-11-08T09:46:34Z Indexed on 2012/11/08 11:06 UTC
Read the original article Hit count: 397

Filed under:

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

© Server Fault or respective owner

Related posts about bash