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

如何编写Git钩子,检出存有stash的分支时给出提示?

实现Git分支切换时的stash提示钩子
  • 步骤1:进入目标仓库的钩子目录
    打开终端,切换到你的Git仓库根目录,进入钩子文件夹:

    cd .git/hooks
    
  • 步骤2:创建post-checkout钩子脚本
    创建并编辑post-checkout文件(无后缀),写入以下内容:

    #!/bin/bash
    
    # 获取当前分支名称
    current_branch=$(git rev-parse --abbrev-ref HEAD)
    
    # 统计当前分支关联的stash条目数量
    stash_count=$(git stash list | grep -c "On $current_branch:")
    
    # 如果存在stash,输出提示
    if [ $stash_count -gt 0 ]; then
        echo "You have $stash_count stash on this branch, use `git stash pop` to unstash it."
    fi
    
  • 步骤3:赋予脚本可执行权限
    在终端执行命令添加执行权限:

    chmod +x post-checkout
    

额外说明

  • 这个钩子会在git checkout切换分支完成后自动触发,只会统计当前分支创建的stash条目,不会误报其他分支的暂存内容。
  • 若要让所有Git仓库默认启用该钩子:
    1. 创建全局钩子模板目录:mkdir -p ~/.git_template/hooks
    2. 将上述post-checkout脚本复制到~/.git_template/hooks/目录,并赋予可执行权限
    3. 配置Git使用该模板:git config --global init.templatedir '~/.git_template'
      新克隆或初始化的仓库会自动带上这个钩子,已有的旧仓库需要手动复制脚本到对应.git/hooks目录。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 12:25:58