4

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
  • 71
  • 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

10

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

#!/bin/sh

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

if echo "$WORD_LIST" | grep -qw "$MATCH"; then
    echo "found"
else
    echo "not found"
    exit 1
fi
coolaj86
  • 74,004
  • 20
  • 105
  • 125
Marco Silva
  • 323
  • 1
  • 6