代码之家  ›  专栏  ›  技术社区  ›  Alexander Mills

bash测试-匹配正向斜杠

  •  1
  • Alexander Mills  · 技术社区  · 6 年前

    我有一个git分支名称:

    current_branch='oleg/feature/1535693040'
    

    我想测试分支名称是否包含/feature/,因此我使用:

    if [ "$current_branch" != */feature/* ] ; then
      echo "Current branch does not seem to be a feature branch by name, please check, and use --force to override.";
      exit 1;
    fi
    

    1 回复  |  直到 6 年前
        1
  •  2
  •   cxw    6 年前

    [ ] test(1) command ,它不像bash那样处理模式。相反,使用双括号 bash conditional expression [[ ]]

    $ current_branch='oleg/feature/1535693040'
    $ [ "$current_branch" = '*/feature/*' ] && echo yes
    $ [[ $current_branch = */feature/* ]] && echo yes
    yes
    

    使用正则表达式:

    $ [[ $current_branch =~ /feature/ ]] && echo yes
    yes
    

    正则表达式可以匹配任何地方,因此不需要前导和尾随 * (这将是 .*

    [[ foo/bar =~ / ]] 返回true。这与许多语言中的正则表达式表示法不同。