Reputation: 28860
I have the following bash code:
if [ $NOD_ENV = "production" ]; then IS_PRODUCTION=1; else IS_PRODUCTION=0; fi
if [ $IS_PRODUCTION ]; then VALUE="$VALUE_PRODUCTION"; else CDN_HEADER_VALUE="$PRODUCTION"; fi
# etc
fi
I am getting some unexpected output assigning variables this way. How could I do this better?
Upvotes: 0
Views: 88
Reputation: 141483
It's a cool trick to set boolean variable in bash to the string "true" or "false":
if [ $NOD_ENV = "production" ]; then IS_PRODUCTION=true; else IS_PRODUCTION=false; fi
if "$IS_PRODUCTION"; then VALUE="$VALUE_PRODUCTION"; else CDN_HEADER_VALUE="$PRODUCTION"; fi;
What happens here, is that IS_PRODUCTION has the string "true" or "false". Once you run if "$IS_PRODUCTION"
the variable is expanded which results in if true
or if false
. true
and false
are builtin commands, which get run, and return - zero status for true
and non-zero status for false
.
Upvotes: 1
Reputation: 236
You need to explicitly test the value of $IS_PRODUCTION
:
if [ $IS_PRODUCTION = 0 ]; then ...
if [ $IS_PRODUCTION ]
only tests whether the length of $IS_PRODUCTION
is non-zero.
As a side note, [ is actually a program, and you can see the options for it by running /usr/bin/[ --help
(the /usr/bin seems important on my system for some reason ...)
Upvotes: 2