bash - 在 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
我错过了什么?
解决方案
您的参考看起来不像 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 语法,它在模式之后只有右括号,并以双分号结尾。
推荐阅读
- javascript - mongo db + node 返回连接字符串
- python-3.x - 使用 Django 信号捕获更改后更改实例值
- reporting-services - SSRS:根据特定值计算行数
- snakemake - Snakemake 帮助功能
- spss - Kaplan Meier,审查数据
- flutter - 是否有任何有用的颤振包来处理用户权限?
- json - Beautifulsoup AJAX 表转 JSON
- sas - 在 SAS proc SQL 中重新创建 Tableau 函数已修复
- powershell - 如何在 powershell 中列出 onedrive 文件夹?
- vb.net - VS 提出这个建议。为什么 distinct 出现两次?