检查列表是否包含特定字符串

时间:2016-09-02 17:51:31

标签: string bash list if-statement comparison

我有两个变量(PACKAGE_NAMEPACKAGE_LIST),我正在尝试检查PACKAGE_LIST是否包含PACKAGE_NAME

这就是我所拥有的:

PACKAGE_LIST="rpm-foo-bar:5.0.1"
PACKAGE_NAME="rpm-foo"

if [[ ${PACKAGE_LIST} =~ "${PACKAGE_NAME}" ]]; then
  echo "PACKAGE_NAME is in PACKAGE_LIST"
else
  echo "PACKAGE_NAME is NOT in PACKAGE_LIST"
fi

我遇到的问题是虽然rpm-foorpm-foo-bar类似,但它不一样,应该落入else语句中(PACKAGE_NAME不在{{1} }})。我尝试在字符串比较中添加PACKAGE_LIST,但只有$PACKAGE_LIST结束时才有效。相反,PACKAGE_NAME附加了一个版本。如何使此检查变得更智能,以便检查属于“PACKAGE_LIST不在PACKAGE_NAME”中?

注意:有时PACKAGE_LIST不会包含版本,如下所示:

PACKAGE_LIST

1 个答案:

答案 0 :(得分:2)

怎么样

[[ ${PACKAGE_LIST} =~ "${PACKAGE_NAME}:" || ${PACKAGE_LIST} == ${PACKAGE_NAME} ]]