首页 > 解决方案 > 在 Windows bash 中查找字符串的一部分

问题描述

我需要将分支名称中的任务代码添加到每个提交中。我们发现这应该用一个钩子来完成。

这是代码:

#!/bin/bash
# Include any branches for which you wish to disable this script
if [ -z "$BRANCHES_TO_SKIP" ]; then
BRANCHES_TO_SKIP=(master develop)
fi
# Get the current branch name and check if it is excluded
BRANCH_NAME=$(git symbolic-ref --short HEAD)
BRANCH_EXCLUDED=$(printf "%s\n" "${BRANCHES_TO_SKIP[@]}" | grep -c "^$BRANCH_NAME$")
# Trim it down to get the parts we're interested in
TRIMMED=$(echo $BRANCH_NAME | sed -e 's:\([a-z]\+\/\)*\([A-Z]\+-[0-9]\+\).\+:\2:')
# If it isn't excluded, preprend the trimmed branch identifier to the given message
if [ -n "$BRANCH_NAME" ] &&  ! [[ $BRANCH_EXCLUDED -eq 1 ]]; then
sed -i.bak -e "1s,^,$TRIMMED: ," $1
fi

现在发生的事情是这样的:

LG-132: LG-132: LG-132: LG-132: LG-132: LG-132: LG-132: 将https://git.dw.com/scm/lg/webapp的分支“开发”合并到发展

因此,每次我进行修改时都会添加分支代码。现在,我正在尝试检查提交消息中是否包含分支代码,如果是,则中断/返回 0。

这是我到目前为止所拥有的:

#!/bin/bash
# Include any branches for which you wish to disable this script
if [ -z "$BRANCHES_TO_SKIP" ]; then
  BRANCHES_TO_SKIP=(master develop)
fi
# Get the current branch name and check if it is excluded
BRANCH_NAME=$(git symbolic-ref --short HEAD)
BRANCH_EXCLUDED=$(printf "%s\n" "${BRANCHES_TO_SKIP[@]}" | grep -c "^$BRANCH_NAME$")
# Trim it down to get the parts we're interested in
TRIMMED=$(echo $BRANCH_NAME | sed -e 's:\([a-z]\+\/\)*\([A-Z]\+-[0-9]\+\).\+:\2:')
# If it isn't excluded, preprend the trimmed branch identifier to the given message
if [ -n "$BRANCH_NAME" ] && ! [[ $BRANCH_EXCLUDED -eq 1 ]]; then
  set BRANCH_NAME|find "$TRIMMED" >nul && shouldAddCode=true || shouldAddCode=false
  if $shouldAddCode; then
    echo "test"
  else
    sed -i.bak -e "1s,^,$TRIMMED: ," "$1"
  fi
fi

我在控制台中得到这个:

查找:'LG-132':没有这样的文件或目录

现在这段代码不起作用。我使用此代码作为参考:

set "i=hello world"
set i|find "world" >nul && set test=yes || set test=no
echo %test%
pause

我错过了什么?

标签: bashgitshellgithooks

解决方案


您的参考看起来不像 bash 代码,而是像 CMD 脚本。

要在 bash 脚本中检查某个变量是否以特定字符串开头,规范的方法是 as case...esac构造,例如:

case "$BRANCHNAME" in
"$TRIMMED"*)
  # yes, it's there
  echo "test"
  ;;
*)
  # no, it's not there; add it
  if ! [[ $BRANCH_EXCLUDED -eq 1 ]]; then
    sed -i.bak -e "1s,^,$TRIMMED: ," "$1"
  fi
  ;;
esac

请注意奇怪的 case arm 语法,它在模式之后只有右括号,并以双分号结尾。


推荐阅读