10

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

13

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
  • 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
  • @Jonik - please accept one of the answers if it meets your needs so that others know that your issue has been resolved. Thanks. – slm Oct 2 '13 at 2:30
  • 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
8

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 ))
  • 1
    The former is not ternary. true && false || echo "if this was ternary, this wouldn't be executed" – Chris Down Sep 20 '13 at 9:01
  • @chris - true, but it's still a good practical answer even if the terminology isn't quite right. – cas Sep 20 '13 at 9:09
  • @CraigSanders The terminology matters -- I see this used way too often in scripts when the second command can fail. – Chris Down Sep 20 '13 at 9:11
  • @ChrisDown: Make the editing to the answer, is it better now? – cuonglm Feb 13 '16 at 2:57
  • 1
    Lol for the 2.5 years it took for cuonglm's edit! – iruvar Feb 13 '16 at 4:04
3

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.