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.)

3 Answers 3

32

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]
3
  • 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
    Commented Sep 20, 2013 at 9: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
    Commented Oct 7, 2013 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
    Commented Oct 7, 2013 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 ))
0
10

You can use the && and || operators

[ "$MYAPP_ENV" == "PROD" ] && [email protected] || [email protected]

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .