检查是否有任何列表项匹配变量

问题描述 投票:0回答:1

目标是验证字符串是否与任何列表项匹配。

这与检查列表中是否存在变量

相反

代码应类似于:

email="[email protected]"
list=["app-1", "app-2", "john"]

if [ $email -contains $list]; then
  echo "email contains variable from list"
else
  echo "email does not contain any of list items"
fi

# Item1: false -> email does not contains "app-1"
# Item2: false -> email does not contains "app-2"
# Item3: true  -> email contains "john"
bash list
1个回答
0
投票

尝试:

#!/bin/bash

email="[email protected]"
list=("app-1" "app-2" "john")

found=false

for item in "${list[@]}"; do
  if [[ $email == *"$item"* ]]; then
    echo "Found!"
    found=true
    break
  fi
done

if [ $found == false ]; then
  echo "Not found."
fi
© www.soinside.com 2019 - 2024. All rights reserved.