如何判断一个字符串是否包含Unix shell脚本中的另一个字符串?

前端之家收集整理的这篇文章主要介绍了如何判断一个字符串是否包含Unix shell脚本中的另一个字符串?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想写一个Unix shell脚本,如果在另一个字符串内部有一个字符串,它会做各种逻辑。例如,如果我在某个文件夹,分支。有人可以告诉我如何完成这个吗?如果可能,我想让这不是shell具体(即不是bash只)但如果没有其他方式,我可以做到这一点。
#!/usr/bin/env sh

if [ "$PWD" contains "String1" ]
then
    echo "String1 present"
elif [ "$PWD" contains "String2" ]
then
    echo "String2 present"
else
    echo "Else"
fi
这里是另一个解决方案。这使用 POSIX substring parameter expansion,所以它工作在bash,dash,ksh …
test "${string#*$word}" != "$string" && echo "$word found in $string"

编辑:这是一个好主意,C.罗斯。这里是一个功能版本有一些例子:

# contains(string,substring)
#
# Returns 0 if the specified string contains the specified substring,# otherwise returns 1.
contains() {
    string="$1"
    substring="$2"
    if test "${string#*$substring}" != "$string"
    then
        return 0    # $substring is in $string
    else
        return 1    # $substring is not in $string
    fi
}

contains "abcd" "e" || echo "abcd does not contain e"
contains "abcd" "ab" && echo "abcd contains ab"
contains "abcd" "bc" && echo "abcd contains bc"
contains "abcd" "cd" && echo "abcd contains cd"
contains "abcd" "abcd" && echo "abcd contains abcd"
contains "" "" && echo "empty string contains empty string"
contains "a" "" && echo "a contains empty string"
contains "" "a" || echo "empty string does not contain a"
contains "abcd efgh" "cd ef" && echo "abcd efgh contains cd ef"
contains "abcd efgh" " " && echo "abcd efgh contains a space"
原文链接:https://www.f2er.com/bash/391842.html

猜你在找的Bash相关文章