Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

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 ]];
  then
    usage
fi

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. Full script can be seen at pastebin.

+ ENVT=stage
+ ACTION=stop
+ USER=www
+ '[' 2 -ne 2 ']'
+ [[ stage != qa ]]
+ usage
share|improve this question
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. –  user3757638 Jul 29 '14 at 18:19

2 Answers 2

up vote 3 down vote accepted

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

case "$ENVT" in
  (qa|qa2|stageqa|stage) ;;
  (*) usage ;;
esac
share|improve this answer
    
I tried using case originally, but I'm not as familiar with it as if statements. Thanks for giving me the better solution. –  user3757638 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 ]];
then
    usage
fi

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.

share|improve this answer
    
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

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.