26

In a bash script, I'm assigning a local variable so that the value depends on an external, global environment variable ($MYAPP_ENV).

if [ "$MYAPP_ENV" == "PROD" ]
then
    [email protected]
else
    [email protected]
fi

Is there a shorter (yet clean) way to write the above assignment? (Presumably using some kind of conditional operator / inline if.)

slm
  • 363,520
  • 117
  • 767
  • 871
Jonik
  • 1,460
  • 3
  • 13
  • 17

3 Answers3

31

You could also use a case/switch in bash to do this:

case "$MYAPP_ENV" in
 PROD) SERVER_LOGIN="[email protected]" ;;
    *) SERVER_LOGIN="[email protected]" ;;
esac

Or this method:

[ "$MYAPP_ENV" = PROD ] &&
   [email protected] ||
   [email protected]
Stéphane Chazelas
  • 522,931
  • 91
  • 1,010
  • 1,501
slm
  • 363,520
  • 117
  • 767
  • 871
  • 3
    A case statement is far more readable than jamming it all into one line (which can end in catastrophe if the second command can fail, in this case, it is fine, but getting into that habit can be costly). This is the best method when dealing with cases like this. – Chris Down Sep 20 '13 at 09:02
  • I guess the case statement is the cleanest of the options presented, even if it isn't exactly what I was looking for. Oh well, Bash syntax is awkward, can't get around that. :) – Jonik Oct 07 '13 at 18:52
  • 2
    @Jonik - that's been my finding as well. Believe me I've looked for alternatives, I prefer wide lines that do a lot rather than long programs, and the if/then/else is very verbose for my tastes too. – slm Oct 07 '13 at 19:24
12

Try:

[ condition ] && var=value_when_true || var=value_when_false

If your assignment is numeric, you can use bash ternary operation:

(( assign_condition ? value_when_true : value_when_false ))
cuonglm
  • 150,973
  • 38
  • 327
  • 406
10

You can use the && and || operators

[ "$MYAPP_ENV" == "PROD" ] && [email protected] || [email protected]
MBR
  • 912
  • 10
  • 17