3

I have a bash script and I want to check if a string is in a list. Like: string = "Hello World!", List=("foo", "bar"). Python example:

if name in list: # Another way -> if name in ["foo", "bar"]
  # work to do
else:
  sys.exit(1)

Thank you!

schui
  • 61
  • 1
  • 2
  • 6
  • 1
    we need to see samples of "a string" and "a list". Please edit your Q to include the **small** sampe data set and the required output from that input. Good luck. – shellter Aug 31 '16 at 20:57
  • Added samples for string and list. – schui Aug 31 '16 at 21:28
  • You could (mis)use an associative array for holding the list, where each list element is a key. While defining the list looks a bit ugly, because you must define a dummy value for each key-value-pair in the list, it makes searching easy. See for example [here](http://superuser.com/questions/195598/test-if-element-is-in-array-in-bash). – user1934428 Sep 01 '16 at 06:34

1 Answers1

9

There are a number of ways, the simplest I see is:

WORD_LIST="one two three"
MATCH="two"

if echo $WORD_LIST | grep -w $MATCH > /dev/null; then
    command
else
    exit 1
fi
Marco Silva
  • 313
  • 1
  • 5