Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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

share|improve this question
add comment

2 Answers 2

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.

share|improve this answer
    
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 '12 at 10:03
add comment
up vote 0 down vote accepted

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

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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