0

I have an if condition like this;

if [ "$var" != "something" ] && [ "$var" != "something2" ] && [ "$var" != "something3" ] && [ "$var" != "something4" ]; then
    # do something
fi

Which checks if $var not equals to any of the given parameters then act accordingly. However, this list is actually a lot bigger than the given example so is there a way to list them somewhere and check from that list instead of adding them individually? Similar questions to mine I found online was mostly numbers but my array list will consist of strings so I had to ask this question.

Marry Jane
  • 125
  • 9

1 Answers1

1

Use an associative array with your acceptable values as keys:

#!/usr/bin/env bash
case $BASH_VERSION in ''|[1-3].*) echo "ERROR: Bash 4.0+ required" >&2; exit 1;; esac

declare -A values=(
  ["something"]=1
  ["something2"]=1
  ["something3"]=1
)

if [[ ${values[$var]} ]]; then
  : # do something
fi
Charles Duffy
  • 235,655
  • 34
  • 305
  • 356