Linux - 检查字符串是否在列表中

sch*_*hui 3 linux bash shell

我有一个 bash 脚本,我想检查一个字符串是否在列表中。比如:string = "Hello World!", List=("foo", "bar")。蟒蛇示例:

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

谢谢!

小智 7

有很多方法,我看到的最简单的是:

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

if echo $WORD_LIST | grep -w $MATCH > /dev/null; then
    command
else
    exit 1
fi
Run Code Online (Sandbox Code Playgroud)

  • 只需在 *"$MATCH"*) 中执行 `case $WORD_LIST 就简单多了 ... ;; esac` (2认同)