可以使用第 2.6.2 节,参数扩展中定义grep的唯一符合 POSIX 的方法来匹配字符串中的子字符串,而无需生成子进程(例如) 。sh(1p)
这是一个便利功能:
# Note:
# Unlike a regular expression, the separator *must* enclose the pattern;
# and it could be a multi chars.
isin() {
    PATTERN=${2:?a pattern is required}
    SEP=${3:-|}
    [ -z "${PATTERN##*${SEP}${1}${SEP}*}" ]
}
例子:
for needle in foo bar; do
    isin "$needle" "|hello|world|foo|" && echo "found: $needle"
done
# using ";" as separator
for needle in foo bar; do
    isin "$needle" ";hello;world;foo;" \; && echo "found: $needle"
done
# using the string "RS" as separator
for needle in foo bar; do
    isin "$needle" "RShelloRSworldRSfooRS" RS && echo "found: $needle"
done
case如果您想要两个世界,您可以将此解决方案与语句混合使用:
PATTERN="|foo bar|baz|bla|"
case "$needle" in
    xyz) echo "matched in a static part" ;;
    *)
        if [ -z "${PATTERN##*|${needle}|*}" ]; then
            echo "$needle matched $PATTERN"
        else
            echo "not found"
        fi
esac
笔记
有时最好记住您可以在awk(1p)POSIX 中编写整个脚本,但我相信这是另一个答案。