bash测试 - 匹配正斜杠

问题描述 投票:1回答:1

我有一个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,任何人都知道为什么?

bash shell pattern-matching conditional
1个回答
2
投票

[ ]是单支架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。这与许多语言中的正则表达式不同。

© www.soinside.com 2019 - 2024. All rights reserved.