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

我的Git pre-push钩子shell脚本为何出现解析错误?

Git pre-push钩子解析错误排查

我很少编写shell脚本,这应该是个明显的错误!这个pre-push钩子用于推送时触发逻辑:若当前分支为指定的githook分支,则执行npm run testbuild,执行失败则阻止推送;若在其他分支则不干预,分支正确且测试通过则允许推送。

以下是原pre-push脚本内容:

#!/bin/zsh

current_branch=$(git symbolic-ref HEAD | sed -e 's,.*/\(.*\),\1,')

CMD="npm run testbuild"

if [[ $current_branch = "githook"]]; then
    eCHO "You are on $branch, running build test"
    eval $CMD
    RESULT=$?
    if [ $RESULT -ne 0 ]; then
        echo "failed $CMD"
        exit 1
    fi
fi
exit 0

推送时出现错误:

.git/hooks/pre-push:7: parse error near `;'

错误原因

核心错误在第7行的条件判断语句:if [[ $current_branch = "githook"]];——右方括号]和分号;之间必须添加空格。zsh的语法规则要求[[ ... ]]结构的闭合]后面如果紧跟分号,必须用空格分隔,否则会被解析为非法的语法单元,触发parse error。

另外脚本还有两个次要问题:

  • 第8行的eCHO是大小写错误,shell命令区分大小写,应改为echo
  • 第8行使用了未定义的变量$branch,需替换为之前正确获取分支名的$current_branch

修正后的脚本

#!/bin/zsh

current_branch=$(git symbolic-ref HEAD | sed -e 's,.*/\(.*\),\1,')

CMD="npm run testbuild"

if [[ $current_branch = "githook" ]]; then
    echo "You are on $current_branch, running build test"
    eval $CMD
    RESULT=$?
    if [ $RESULT -ne 0 ]; then
        echo "failed $CMD"
        exit 1
    fi
fi
exit 0

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 17:40:29