萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 伺服器教學

Linux 下 Git 核心配置與實戰技巧全攻略

Git 配置檔案層級與優先順序

Git 設定分三個層級,優先級由高到低:

  1. 專案級:.git/config (僅影響當前倉庫)
  2. 用戶級:~/.gitconfig (加 --global 參數操作)
  3. 系統級:/etc/gitconfig (加 --system 參數,需 root 權限)

後設定者覆蓋先設定者;git config --list 可查看最終生效值。

必做的初始化設定

1. 設定提交者身分 (每次提交都會嵌入)

git config --global user.name "Your Name"
git config --global user.email "you@example.com"

專案需不同身分時,在專案目錄下執行同樣指令並省略 --global。

2. 指定預設編輯器

git config --global core.editor vim

3. 設定合併衝突比較工具

git config --global merge.tool vimdiff

支援 kdiff3、meld、gvimdiff 等。

4. 開啟彩色輸出

git config --global color.ui true

5. 常用別名 (系統級建議)

sudo git config --system alias.st status
sudo git config --system alias.ci commit
sudo git config --system alias.co checkout
sudo git config --system alias.br branch

實戰常見問題與解決

推送被拒:non-fast-forward

# 正確流程
git fetch origin
git merge origin/master   # 或 git rebase origin/master
git push origin master

追蹤單一檔案歷史

  • git log -p "filename":顯示每次提交的完整差異
  • git blame "filename":逐行顯示最後修改提交
  • git show <commit-hash>:查看特定提交詳細內容

版本回退三種方式

指令行為適用場景
git reset --hard <commit_id>HEAD、暫存區、工作區全部回退,歷史重寫本地私有分支,確定不要後續提交
git checkout <commit_id>檢出舊版本到工作區,HEAD 變為分離狀態臨時查看舊代碼,不影響分支歷史
git clean -df刪除未追蹤的檔案/目錄 (慎用)清理編譯產物等雜項

查詢幫助

git help <command>      # 如 git help config
git <command> --help
man git-<command>

離線也能查閱;更深入交流可上 Freenode IRC #git 或 #github。

copyright © 萬盛學電腦網 all rights reserved