【问题标题】:bash wildcard with variables inside an if statement在 if 语句中带有变量的 bash 通配符
【发布时间】:2015-04-11 14:28:03
【问题描述】:

我想根据this solution在字符串中查找子串。

但由于某种原因,它不适用于变量:

str="abcd";
substr="abc";
if [[ "${substr}"* == ${str} ]]
then
        echo "CONTAINS!";
fi

【问题讨论】:

  • substr 必须在 == 之后

标签: string bash if-statement wildcard


【解决方案1】:

在参考手册section Conditional Constructs 中,您将阅读[[ ... ]] 的文档:

当使用==!=操作符时,操作符右边的字符串被认为是一个模式并根据Pattern Matching中描述的规则进行匹配,就像extglob shell 选项已启用。

(强调是我的)。

因此,您需要将 glob 模式放在 == 运算符的右侧

if [[ $str == "$substr"* ]]; then

注意左边不用引用,但右边的$substr部分需要引用,以防它包含像*这样的全局字符, ?[...]+(...)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-20
    • 1970-01-01
    • 1970-01-01
    • 2016-02-18
    • 1970-01-01
    • 2018-07-31
    • 1970-01-01
    • 2019-04-27
    相关资源
    最近更新 更多