bash 测试 - 匹配正斜杠

bash test - match forward slashes

我有一个 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 退出,有人知道为什么吗?

[ ]是单括号test(1) command, which does not handle patterns the same way bash does. Instead, use the double-bracket 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 =~ / ]] returns 为真。这与许多语言中的正则表达式表示法不同。