20

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
    SERVER_LOGIN=foobar123@prod.example.com
else
    SERVER_LOGIN=foobar987@test.example.com
fi

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

29

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

case "$MYAPP_ENV" in
 PROD) SERVER_LOGIN="foobar123@prod.example.com" ;;
    *) SERVER_LOGIN="foobar987@test.example.com" ;;
esac

Or this method:

[ "$MYAPP_ENV" = PROD ] &&
   SERVER_LOGIN=foobar123@prod.example.com ||
   SERVER_LOGIN=foobar987@test.example.com
3
  • 2
    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 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
    Oct 7 '13 at 18:52
  • 1
    @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 7 '13 at 19:24
10

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
8

You can use the && and || operators

[ "$MYAPP_ENV" == "PROD" ] && SERVER_LOGIN=foobar123@prod.example.com || SERVER_LOGIN=foobar987@test.example.com

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.