0

I want to check in my bash script, if a variable is equal to value 1 OR equal to value 2.

I don't want to use something like this, because the 'if true statements' are the same (some big echo texts), when the variable is equal to 1 or 2. I want to avoid data redundancy.

if [ $1 == 1 ] ; then echo number 1 ; else
if [ $1 == 2 ] ; then echo number 2 ; fi

More something like

if [ $1 == 1 OR 2 ] ; then echo number 1 or 2 ; fi
  • Aside: `==` isn't a valid comparison operator inside `[`. Bash allows it as an extension, but the [relevant standard](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/test.html) only specifies `=` for string comparison. – Charles Duffy Jan 25 '17 at 18:39
  • Arguably duplicative of http://stackoverflow.com/questions/21157435/bash-string-compare-to-multiple-correct-values, or http://stackoverflow.com/questions/22259259/bash-if-statement-to-check-if-string-is-equal-to-one-of-several-string-literals – Charles Duffy Jan 25 '17 at 18:43

2 Answers2

3

Since you are comparing integer values, use the bash arithmetic operator (()), as

(( $1 == 1 || $1 == 2 )) && echo "number 1 or 2"

For handling-strings using the regex operator in bash

test="dude"
if [[ "$test" =~ ^(dude|coolDude)$ ]]; then echo "Dude Anyway"; fi
# literally means match test against either of words separated by | as a whole
# and not allow for sub-string matches.
Inian
  • 80,270
  • 14
  • 142
  • 161
  • 1
    `-o` is explicitly marked obsolete in the current revision of the POSIX standard. Use `[ one ] || [ another ]`. And `==` is a nonportable extension; use `=` for string comparisons in `[ ]`. – Charles Duffy Jan 25 '17 at 18:40
  • 1
    (see the `[OB]` markings in http://pubs.opengroup.org/onlinepubs/9699919799/utilities/test.html) – Charles Duffy Jan 25 '17 at 18:41
2

Probably the most easy to extend option is a case statement:

case $1 in
    [12])
        echo "number $1"
esac

The pattern [12] matches 1 or 2. For larger ranges you could use [1-5], or more complicated patterns like [1-9]|[1-9][0-9] to match any number from 1 to 99.

When you have multiple cases, you should separate each one with a ;;.

Tom Fenech
  • 72,334
  • 12
  • 107
  • 141