必须源码编译安装,因CentOS官方源中Git版本严重滞后(CentOS 7为1.8.3.1、CentOS 8为2.18.x),不支持git restore、--filter=tree:0等现代特性,且yum/dnf无法升级至2.43.0等新主版本。

git 在 CentOS 上默认源里的版本普遍偏低(比如 CentOS 7 是 1.8.3.1,CentOS 8 是 2.18.x),而当前最新稳定版已到 2.43.0(截至 2024 年)。如果你需要新功能(如 git switch、git restore)、修复的 CVE 或兼容较新的托管平台(如 Gitee、GitHub 的某些 API 要求),**必须源码编译安装**——包管理器无法满足。
为什么 yum/dnf 安装的 git 版本太旧?
CentOS 的官方仓库以稳定性优先,冻结软件版本。即使你执行 yum update 或 dnf upgrade,git 也不会升级到新主版本。例如:
-
yum info git显示Version: 1.8.3.1(CentOS 7) -
dnf list git显示2.18.4(CentOS 8 Stream)
这些版本不支持 git clone --filter=tree:0、稀疏检出增强、或部分 credential helper 协议,实际使用中容易报错或行为异常。
卸载旧版 git 前必须确认依赖影响
直接 yum remove git 可能连带卸掉 git-core、perl-Git,甚至影响 rpm-build 或某些 CI 工具链。更安全的做法是:
- 先查依赖:
rpm -q --whatrequires git-core - 若输出为空或仅含开发类包(如
git-email),可放心移除 - 执行
yum remove git\*(带星号,清除所有 git 相关子包) - 检查
/usr/bin/git是否已被删除,避免新旧二进制冲突
源码编译安装 git 的关键步骤和坑
核心流程是:装依赖 → 下载源码 → make → make install。但以下几点极易出错:
- 依赖缺
perl-ExtUtils-MakeMaker:会导致make configure失败,报错Can't locate ExtUtils/MakeMaker.pm - 下载地址别用 GitHub archive:它不含 autogen.sh,需手动运行
./configure;推荐用 kernel.org 链接(如wget https://www.kernel.org/pub/software/scm/git/git-2.43.0.tar.gz) -
make prefix=/usr/local install后,/usr/local/bin/git才是新二进制;别漏加/usr/local/bin到$PATH(写入/etc/profile后需source /etc/profile) - 验证时用绝对路径:
/usr/local/bin/git --version,避免 shell 缓存旧命令
如何让系统默认使用新 git 而不是旧残留?
即使新 git 已安装,which git 仍可能返回 /usr/bin/git(旧版)。原因通常是 PATH 顺序或 shell hash 缓存:
- 运行
hash -d git清除命令缓存 - 确认
echo $PATH中/usr/local/bin在/usr/bin之前 - 检查是否有 alias:
alias git,若有则临时取消unalias git - 最稳妥方式:建立软链
ln -sf /usr/local/bin/git /usr/bin/git(需 root 权限)
注意:软链覆盖系统命令有风险,建议仅在明确无其他服务强依赖旧版时操作。


















