0

I know that the =~ operator can be used to identify that a string is in a list...

if [[ "$var" =~ ^(str1|str2|str3)$ ]]
     then
          echo "$var is in the list"
     else
          echo "$var is not in the list"
fi

...but this syntax is not efficient if I am only interested in the else:

if [[ "$var" =~ ^(str1|str2|str3)$ ]]
     then
          echo "foo" >/dev/null        #bogus anything to avoid empty "then" clause
     else
          my_awesome_function_here
fi

I know that if I was just checking against a single string, the != operator could be used...

if [[ "$var" != "str1" ]]; then
     my_awesome_function
fi

...but !=~ is not a valid operator.

Is there an equivalent to !=~? Is there something else I'm missing?

  • If you've declared an associative array, as in `declare -A items=( [str1]=1 [str2]=1 [str3]=1 )`, then `[[ ${items[$var]} ]]` or `! [[ ${items[$var]} ]]` is considerably easier to maintain. (You don't need to worry about part of a string in an associative array having meaning as a regex!) – Charles Duffy Aug 01 '18 at 22:42
  • Oh awesome! I was unaware of the `if ! [[ ... ]]` functionality. Thanks! – NomadGnome Aug 01 '18 at 22:42
  • `!` isn't specific to `[[`; you can use it with *any* command. (And yes, `if` will work with any command; that's why `if grep ...` is valid syntax, same as `if ! grep ...`). – Charles Duffy Aug 01 '18 at 22:43
  • Thanks for the info! And I'm using bash 3, so unfortunately I don't believe I can utilize associative arrays... :( – NomadGnome Aug 01 '18 at 22:45
  • ahh -- yup. Blame Apple for being unwilling to ship GPLv3-licensed code. :/ – Charles Duffy Aug 01 '18 at 22:46
  • BTW, about the empty-clause thing, consider using `:` -- it's a synonym to `true` traditionally given that kind of noop placeholder usage, and it's faster to invoke it than to need to open `/dev/null` as stdout to run `echo` as shown in the current code. – Charles Duffy Aug 01 '18 at 22:47
  • Ah sweet, that's also really helpful. Many thanks!! – NomadGnome Aug 01 '18 at 22:52

0 Answers0