2

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

2 Answers 2

2

I think I figured it out:

TARGET_VAR="$(eval "echo \${MYVAR_${USER_INPUT^^}-$MYVAR_DEFAULT}")"
somecommand -foo "$(eval "echo \${MYVAR_${USER_INPUT^^}-$MYVAR_DEFAULT}")"

It is bash compatible. Without ${USER_INPUT^^} it works in sh too. Its not too beautiful, but working ;)

USER_INPUT is only set by trustworthy users, so it will be fine

1

A case statement can handle even more variants.

#!/bin/bash

MYVAR_DEFAULT=123
MYVAR_FOO=456

echo "Input: "
read USER_INPUT

case $USER_INPUT in

foo)
  TARGET_VAR=$MYVAR_FOO
  ;;
bar)
  TARGET_VAR=$MYVAR_DEFAULT
  ;;
*)
  TARGET_VAR=DEFAULT
  ;;
esac

echo $TARGET_VAR

You can adapt this to your needs - wrap it in a function or whatever.

1
  • Thanks for your answer. unfortunately it does not fit my needs. Sorry for inconvenience. I restated my needs in the question: 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 without changing the scripts, in this example there would be an implicit profile named BAZ, too, all variables to their default values.
    – krissi
    Nov 8, 2012 at 10:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.