Git 是現代軟件開發的核心基礎設施。本文面向 Linux(以 CentOS/Ubuntu 為例)環境,涵蓋 源碼編譯安裝、全局配置、倉庫初始化、提交/分支/遠端協作、常見問題排查,適合從零開始建立團隊 Git 規範的開發者。
| 方式 | 命令 | 優點 | 缺點 |
|---|---|---|---|
| 包管理器 | yum install git / apt install git | 一鍵安裝、自動依賴、易更新 | 版本可能較舊(如 CentOS 7 默認 1.8.x) |
| 源碼編譯 | 見下文 | 獲取最新特性、可定製安裝路徑 | 需手動處理依賴、升級繁瑣 |
| 第三方倉庫 | yum install -y https://packages.endpointdev.com/rhel/7/os/x86_64/endpoint-repo.x86_64.rpm && yum install git | 較新穩定版 | 依賴外部源 |
# 1. 安裝依賴 yum install -y curl-devel expat-devel gettext-devel openssl-devel zlib-devel perl-ExtUtils-MakeMaker gcc make # 2. 下載並編譯 cd /usr/local/src wget https://mirrors.edge.kernel.org/pub/software/scm/git/git-2.45.0.tar.gz tar -xzf git-2.45.0.tar.gz cd git-2.45.0 ./configure --prefix=/usr/local/git # 指定安裝目錄 make -j$(nproc) make install # 3. 配置環境變量 echo 'export PATH=/usr/local/git/bin:$PATH' > /etc/profile.d/git.sh source /etc/profile.d/git.sh # 4. 驗證 git --version # 2.45.0 which git # /usr/local/git/bin/git
git config --global user.name "Your Name" git config --global user.email "you@example.com" git config --global core.editor vim git config --global init.defaultBranch main # Git 2.28+ 默認主分支名 git config --global color.ui auto git config --global push.default simple # 推送當前分支到同名上游 # 查看配置 git config --list --show-origin
配置文件位置:~/.gitconfig(用戶級)、/etc/gitconfig(系統級)、.git/config(倉庫級)。
# 1. 初始化 cd /path/to/project git init # 生成 .git 目錄 # 2. 添加與提交 git add . # 暫存所有變更 git commit -m "Initial commit" # 3. 查看狀態/歷史 git status git log --oneline --graph --decorate --all git diff # 工作區 vs 暫存區 git diff --staged # 暫存區 vs 最後提交
# 功能分支 git checkout -b feature/login # 開發... git add . && git commit -m "feat: add login page" git checkout main git merge --no-ff feature/login # 保留分支歷史 git branch -d feature/login # 熱修復分支 git checkout -b hotfix/fix-typo main git commit -am "fix: typo in README" git checkout main && git merge --no-ff hotfix/fix-typo git tag v1.0.1 git checkout develop && git merge hotfix/fix-typo git branch -d hotfix/fix-typo
# 關聯遠端 git remote add origin git@github.com:user/repo.git git remote -v # 首次推送 git push -u origin main # 日常同步 git pull --rebase origin main # 變基拉取,歷史更乾淨 git push # 標簽推送 git push origin --tags
| 現象 | 原因/解決 |
|---|---|
| 提交時提示 "Please tell me who you are" | 未設置 user.name/email,執行 git config --global ... |
| 拒絕合併無關歷史 | git pull origin main --allow-unrelated-histories |
| 大文件推送失敗 | 配置 Git LFS:git lfs track "*.psd" |
| Windows 換行符警告 | git config --global core.autocrlf input (Linux/Mac) |
| 誤提交敏感信息 | git filter-repo --path .env --invert-paths 重寫歷史(謹慎) |
yum install tig。建立統一的 Git 規範(提交信息格式、分支命名、Code Review 流程),比單純掌握命令更重要。