I'm working on a bash script to restart multiple apache instances in different environments. It's working fine except I'd like to add some logic to ensure only correct arguments are entered. I've tried the below statement in multiple ways, but I'm not having any luck. Any suggestions?

if [[ $ENVT != qa || $ENVT != qa2 || $ENVT != stageqa || $ENVT != stage ]];

It's when I use the stage environment it's evaluating the first option and invoking the function instead of iterating through as seen with set -x turned on.

+ ENVT=stage
+ ACTION=stop
+ USER=www
+ '[' 2 -ne 2 ']'
+ [[ stage != qa ]]
+ usage
  • 1
    || means "or". Your if statement will always be true, since ENVT can't be equal to more than one different string. You probably want if ! [[ $ENVT = qa || $ENVT = qa2 || $ENVT = stageqa || $ENVT = stage ]]; then usage; fi – Mark Plotnick Jul 29 '14 at 18:00
  • Thanks, Mark. I knew there was a way, but I wasn't thinking about how the expression was being evaluated. – DFresh Jul 29 '14 at 18:19

You should not use multiple if condition in this case, use case instead:

case "$ENVT" in
  (qa|qa2|stageqa|stage) ;;
  (*) usage ;;
  • I tried using case originally, but I'm not as familiar with it as if statements. Thanks for giving me the better solution. – DFresh Jul 29 '14 at 18:20

I expected the qa, qa2 etc to be dummy values for more complex tests. If they are just actual values, the solution of @Gnouc is much better obviously.
I'll leave this answer here for educational value related to the original examples syntax.

You would want an "and" for use with the "!=".

Then, you should not chain many expressions or operators together, but use separate tests like this (it's related to the quotes):

if [[ a1 != b1 ]] && [[ a2 != b2 ]] && [[ a3 != b3 ]] ...

Something like:

if [[ "$ENVT" != qa ]] && [[ "$ENVT" != qa2 ]] && [[ "$ENVT" != stageqa ]] && [[ "$ENVT" != stage ]];

I added quotes around the variables as you see. This is not strictly necessary inside of the double [[ ]], but almost anywhere else, for example in [ ], which are very similar. It's hard enough to get used to always quote, so I'll just keep the quotes.

  • You don't need double quote variable in [[..]]. – cuonglm Jul 29 '14 at 18:10
  • @Gnouc Thanks, was actually just trying to find that fact in the bash manpage :) – Volker Siegel Jul 29 '14 at 18:12

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.