You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Git提交模板中${BRANCH_NAME}未自动替换为当前分支名求助

问题描述

Git版本为2.39.0,已配置提交模板为.gitmessage,相关配置输出如下:

deepvision@ubuntu:~/source/repos/dv-detector/dv_ui$ git version
git version 2.39.0
deepvision@ubuntu:~/source/repos/dv-detector/dv_ui$ git config --list |grep template
commit.template=.gitmessage

.gitmessage文件内容:

# Description of the changes made in this commit

## Type of change
- [ ] Bug fix
- [ ] New feature
- [ ] Breaking change

## Related issues
- Fixes #ISSUE_NUMBER
- Implements #ISSUE_NUMBER

## Current branch
Branch: ${BRANCH_NAME}

执行git commit后,模板中的${BRANCH_NAME}并未替换为当前分支名称。

解决方法

Git默认不会自动替换提交模板中的占位符变量,需要借助prepare-commit-msg钩子实现替换逻辑:

  1. 进入本地Git仓库的.git/hooks目录:
cd .git/hooks
  1. 创建prepare-commit-msg脚本文件,写入以下内容:
#!/bin/sh

# 获取当前分支名称
BRANCH_NAME=$(git rev-parse --abbrev-ref HEAD)

# 将模板中的${BRANCH_NAME}替换为实际分支名
sed -i.bak "s/\${BRANCH_NAME}/${BRANCH_NAME}/" "$1"
  1. 给脚本添加执行权限:
chmod +x prepare-commit-msg

之后再执行git commit时,模板里的${BRANCH_NAME}就会被自动替换为当前分支的名称。

注:脚本中的sed -i.bak是为了兼容macOS系统的sed语法,若使用Linux系统,可简化为sed -i "s/\${BRANCH_NAME}/${BRANCH_NAME}/" "$1"。

内容的提问来源于stack exchange,提问作者黄滨滨

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 22:50:22