Git 是目前最流行的分散式版本控制系統,廣泛用於原始碼管理、文件版本追蹤與團隊協作。本文系統整理 Git 的安裝、配置、三大配置層級、使用者管理、別名設定與核心工作流程,幫助初學者快速上手。

一、Git 安裝
# Ubuntu/Debian
apt-get update && apt-get install -y git
# CentOS/RHEL
yum install -y git
# 驗證安裝
git --version
官方下載:https://git-scm.com/download/
二、Git 配置(git config)
查詢說明文件
git config --help
git help config
三大配置層級(優先級由高到低)
| 層級 | 範圍 | 配置檔位置 | 指令參數 |
| local | 當前倉庫 | .git/config | --local(預設) |
| global | 當前使用者 | ~/.gitconfig | --global |
| system | 全系統所有使用者 | /etc/gitconfig | --system |
基本身份配置(首次使用必做)
git config --global user.name "Your Name"
git config --global user.email "you@example.com"
# 查看已配置
git config --global --list
三、使用者名稱增刪改查
# 新增/修改
git config --global --add user.name "New Name"
git config --global user.name "New Name" # 直接設定會覆蓋
# 刪除
git config --global --unset user.name
# 查詢
git config --global --get user.name
git config --global --list
四、指令別名(提升效率神器)
# 常用別名建議
git config --global alias.co "checkout"
git config --global alias.br "branch"
git config --global alias.ci "commit"
git config --global alias.st "status"
git config --global alias.unstage "reset HEAD --"
git config --global alias.last "log -1 HEAD"
git config --global alias.lg "log --oneline --graph --decorate --all"
# 使用方式
git co main
git st
git lg
五、Git 核心工作流程
1. 初始化/克隆倉庫
git init # 當前目錄建立新倉庫
git clone # 克隆遠端倉庫
2. 基本操作循環
# 檢查狀態
git status
# 加入暫存區
git add # 指定檔案
git add . # 所有變更
# 提交
git commit -m "提交訊息"
git commit -am "訊息" # 直接提交已追蹤檔案的修改(跳過 add)
# 查看歷史
git log
git log --oneline --graph --all
3. 分支管理
git branch # 列出本地分支
git branch -a # 含遠端分支
git branch # 建立分支
git checkout # 切換分支
git checkout -b # 建立並切換
git merge # 合併分支
git branch -d # 刪除分支(已合併)
git branch -D # 強制刪除
4. 遠端同步
git remote -v # 查看遠端
git fetch origin # 取得遠端更新(不合併)
git pull origin main # 取得並合併
git push origin main # 推送至遠端
git push -u origin # 首次推送並設定上游
六、實用進階技巧
| 需求 | 指令 |
| 修改最後一次提交訊息 | git commit --amend -m "新訊息" |
| 撤銷工作區修改 | git checkout -- |
| 撤銷暫存區修改 | git reset HEAD |
| 重設至指定提交(保留修改) | git reset |
| 硬重設(捨棄所有修改) | git reset --hard |
| 暫存當前進度 | git stash / git stash pop |
| 查看差異 | git diff / git diff --cached |
| 標籤管理 | git tag v1.0 / git push --tags |
七、.gitignore 範例
# 忽略編譯產物
*.class
target/
build/
# 忽略 IDE 設定
.idea/
.vscode/
*.swp
# 忽略敏感檔案
.env
*.key
config/local.json
掌握上述核心操作,即可應對 90% 的日常 Git 使用場景。建議動手實作幾次完整的「分支開發 → 提交 → 合併 → 推送」流程,建立肌肉記憶。