1

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.

3
  • Why would it make a difference whether they're numbers or strings? The logic is the same. Commented Apr 14, 2020 at 0:04
  • Which version of bash? Can you rely on version 4 or newer? Commented Apr 14, 2020 at 0:04
  • @CharlesDuffy version 4.3.48(1)-release Commented Apr 14, 2020 at 0:06

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.