Search code examples
bash

Multiple conditions variables in bash script


I need to do this:

if [ $X != "dogs" and "birds" and "dogs" ]
then
    echo "it's is a monkey"
fi

with bash script. How to proceed?


Solution

  • You need to turn each option into a separate conditional expression, and then join them together with the && (AND) operator.

    if [[ $X != dogs && $X != birds && $X != cats ]]; then
      echo "'$X' is not dogs or birds or cats.  It must be monkeys."
    fi
    

    You can also do this with single [...], but then you have to quote the parameter expansions, use a separate set of brackets for each comparison, and put the &&s outside them:

    if [ "$X" != dogs ] && [ "$X" != birds ] && [ "$X" != cats ]; then
    

    Note that you don't need double-quotes around single-word literal strings like dogs, but you do need them around parameter expansions (variables) like $X inside the single-bracket version, because otherwise a space in the value of the parameter will cause a syntax error.

    The shell operator version of OR is ||, which works the same way.

    As a side note, it's better stylistically to use lowercase for regular variable names in shell scripts; all-caps names are best reserved for variables that come in from the environment, like $PATH and $TERM and so on. I'd use a more meaningful name like $animal here, but eve if I went with a generic $x, I wouldn't capitalize it.