Bash – Conditional assignment based on environment variable

assignmentbashenvironment-variablesshell-script

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

Best Answer

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
Related Question