0
  : ${models:=foo bar foobar baz}
  : ${special_list:=station_tracks user_features}

   for model in $models;

  do
      echo $model
    if # model in special list; then # how do i test this?
       # do something 
        continue

    fi
done

So, basically how do i test whether the variable model is in special_list or not?

frazman
  • 27,605
  • 60
  • 159
  • 243
  • 2
    See [Check if an array contains a value](http://stackoverflow.com/a/8574392/3030305) – John1024 Jul 17 '15 at 00:26
  • ...though `models` isn't an array here -- it's just a string, which makes it a bit different from that other question -- it *should* be; ie. if this were written according to best practices, it would be an array, and would be a proper duplicate. – Charles Duffy Jul 17 '15 at 23:52
  • Personally, I'd build `special_list` as an associative array, if its purpose were fast lookups: `declare -A special_list=( [station_tracks]=1 [user_features]=1 )`; then, one can use `if [[ ${special_list[$model]} ]]` to do a membership check in constant time. – Charles Duffy Jul 17 '15 at 23:55

1 Answers1

0

Perl has the SmartMatch operator ~~. As has been noted, Bash and not even Awk have an equivalent, however you could use grep as a workaround. Also before I continue, if you are going to use a Bash array, use a Bash array. Your syntax is going to break horribly once something beyond the most simple example, like a space, gets involved:

models=(foo bar foobar baz)
special_list=(station_tracks user_features)
for model in "${models[@]}"
do
  echo "$model"
  if printf '%s\0' "${special_list[@]}" | grep -Fqxz "$model"
  then
    continue
  fi
done

If you prefer you can use equivalent long options:

--fixed-strings --quiet --line-regexp --null-data
Community
  • 1
  • 1
Steven Penny
  • 82,115
  • 47
  • 308
  • 348
  • 1
    The "use an array" advice is good; the "shell out to grep" advice... that's a pretty huge performance hit to take. Yes, grep is faster once it's running, but the constant-time startup overhead for the fork/exec will buy a whole lot of O(n) iteration in native bash. – Charles Duffy Jul 17 '15 at 23:54
  • Heh. I assumed that the outer iteration was needed for some other purpose -- you're right that if it's only being done for the purpose of the join, we're in a different world. (I'd consider using `comm` rather than `grep` in that case, to be eating fork overhead only once rather than once per model). – Charles Duffy Jul 17 '15 at 23:59