Git 指令速查

Git 完整指令參考手冊,涵蓋基本操作、分支管理、進階技巧與問題排查


目錄

  1. 基本設定與 Alias
  2. 建立與複製
  3. 基本操作
  4. 分支操作
  5. Rebase 變基
  6. Reset 重設
  7. 實戰範例
  8. 最佳實踐
  9. 常見問題
  10. 總結

基本設定

# 設定使用者資訊
git config --global user.name "你的名字"
git config --global user.email "your@email.com"

# 查看設定
git config --list
git config user.name

# 設定預設編輯器
git config --global core.editor "vim"

# 設定別名(Alias)
git config --global alias.st status
git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.cm commit

# === 推薦的 Commit & Push Alias ===

# 基本 commit
git config --global alias.c 'commit'
git config --global alias.ca 'commit -a'                    # commit 所有已追蹤檔案
git config --global alias.cm 'commit -m'                    # commit 帶訊息
git config --global alias.cam 'commit -am'                  # add + commit
git config --global alias.amend 'commit --amend'            # 修改最後一個 commit
git config --global alias.amendne 'commit --amend --no-edit'  # 修改但不改訊息

# 快速 commit(常用!)
git config --global alias.ac '!git add -A && git commit -m'  # add 全部並 commit
git config --global alias.save '!git add -A && git commit -m "save"'  # 快速儲存

# Push 相關
git config --global alias.p 'push'
git config --global alias.po 'push origin'
git config --global alias.pom 'push origin main'            # push 到 main
git config --global alias.pu 'push -u origin'               # push 並設定 upstream
git config --global alias.pf 'push --force-with-lease'      # 安全的 force push
git config --global alias.pt 'push --tags'                  # push tags

# Pull 相關
git config --global alias.pl 'pull'
git config --global alias.plo 'pull origin'
git config --global alias.plom 'pull origin main'
git config --global alias.plr 'pull --rebase'               # pull 用 rebase

# 組合指令(超方便!)
git config --global alias.acp '!git add -A && git commit -m "$1" && git push'  # add + commit + push
git config --global alias.sync '!git pull --rebase && git push'  # 同步(拉取並推送)
git config --global alias.update 'pull --rebase origin main'     # 更新主分支

# Status 相關
git config --global alias.s 'status -s'                     # 簡短狀態
git config --global alias.ss 'status'                       # 完整狀態

# Log 相關
git config --global alias.l 'log --oneline'
git config --global alias.lg "log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit"
git config --global alias.last 'log -1 HEAD'                # 顯示最後一個 commit
git config --global alias.ls 'log --pretty=format:"%C(yellow)%h%Cred%d\\ %Creset%s%Cblue\\ [%cn]" --decorate'

# 分支相關
git config --global alias.b 'branch'
git config --global alias.ba 'branch -a'                    # 所有分支
git config --global alias.bd 'branch -d'                    # 刪除分支
git config --global alias.bD 'branch -D'                    # 強制刪除分支

# Checkout/Switch
git config --global alias.sw 'switch'
git config --global alias.swc 'switch -c'                   # 建立並切換分支

# Diff
git config --global alias.d 'diff'
git config --global alias.ds 'diff --staged'                # 查看已暫存的差異

# 其他實用
git config --global alias.unstage 'reset HEAD --'           # 取消暫存
git config --global alias.undo 'reset --soft HEAD~1'        # 撤銷最後一個 commit
git config --global alias.discard 'checkout --'             # 放棄工作區修改
git config --global alias.aliases "config --get-regexp '^alias\.'"  # 顯示所有 alias

使用範例

# 快速 commit 並 push(最常用!)
git ac "feat: 新增登入功能"      # add 全部並 commit
git p                            # push

# 或一行搞定
git acp "feat: 新增登入功能"     # add + commit + push

# 快速儲存工作
git save                         # add 全部並 commit "save"

# 修改最後一個 commit
git amend                        # 開啟編輯器修改訊息
git amendne                      # 不修改訊息,只加入新變更

# Push 相關
git pom                          # push origin main
git pu feature-branch            # push -u origin feature-branch

# 同步分支
git sync                         # pull --rebase && push

# 查看狀態和歷史
git s                            # 簡短狀態
git lg                          # 漂亮的 log 圖形

# 撤銷操作
git undo                         # 撤銷最後一個 commit(保留變更)
git unstage file.txt             # 取消暫存

查看已設定的 Alias

# 顯示所有 alias
git aliases

# 或直接查看
git config --get-regexp alias

# 查看特定 alias
git config alias.ac

移除 Alias

# 移除特定 alias
git config --global --unset alias.ac

# 編輯 .gitconfig 檔案
vim ~/.gitconfig
# 或
code ~/.gitconfig

建立與複製

# 初始化本地 repo
git init

# 複製遠端 repo
git clone https://github.com/user/repo.git

# 複製並指定目錄名稱
git clone https://github.com/user/repo.git my-folder

基本操作

# 查看狀態
git status
git status -s  # 簡短格式

# 加入暫存區
git add file.txt           # 加入特定檔案
git add .                  # 加入所有變更
git add *.js               # 加入所有 .js 檔案
git add -p                 # 互動式選擇要加入的部分

# Commit
git commit -m "訊息"
git commit -am "訊息"      # 加入已追蹤檔案並 commit
git commit --amend         # 修改最後一個 commit

# 移除檔案
git rm file.txt            # 刪除檔案並加入暫存區
git rm --cached file.txt   # 停止追蹤但保留檔案

# 移動/重新命名
git mv old.txt new.txt

分支操作

# 查看分支
git branch                 # 本地分支
git branch -r              # 遠端分支
git branch -a              # 所有分支
git branch -v              # 顯示最後一個 commit

# 建立分支
git branch feature         # 建立分支(不切換)
git checkout -b feature    # 建立並切換分支
git switch -c feature      # 新語法:建立並切換

# 切換分支
git checkout main
git switch main            # 新語法

# 刪除分支
git branch -d feature      # 刪除已合併的分支
git branch -D feature      # 強制刪除

# 重新命名分支
git branch -m old-name new-name

合併與整合

# 合併分支
git merge feature          # 合併 feature 到當前分支
git merge --no-ff feature  # 不使用 fast-forward
git merge --squash feature # 壓縮成一個 commit

# 取消合併
git merge --abort

Remote 操作

# 查看 remote
git remote -v

# 新增 remote
git remote add origin https://github.com/user/repo.git

# 移除 remote
git remote remove origin

# 重新命名 remote
git remote rename origin upstream

# 修改 remote URL
git remote set-url origin https://new-url.git

# 查看 remote 詳細資訊
git remote show origin

Push 與 Pull

# Push
git push origin main
git push -u origin main    # 設定 upstream 並 push
git push --all             # push 所有分支
git push --tags            # push 所有 tags
git push --force           # 強制 push(危險!)
git push --force-with-lease # 較安全的強制 push

# Pull
git pull origin main
git pull --rebase          # 使用 rebase 而非 merge

# Fetch
git fetch origin           # 抓取但不合併
git fetch --all            # 抓取所有 remote
git fetch --prune          # 刪除已不存在的遠端分支

Log - 查看歷史記錄

git log(Commit 歷史)

# 基本 log
git log                    # 完整歷史
git log -5                 # 最近 5 筆
git log --oneline          # 單行顯示
git log --graph            # 圖形化顯示
git log --all              # 所有分支

# 組合使用
git log --oneline --graph --all --decorate

# 查看特定檔案
git log file.txt
git log -p file.txt        # 顯示差異

# 查看作者
git log --author="John"

# 查看時間範圍
git log --since="2 weeks ago"
git log --after="2024-01-01" --before="2024-12-31"

# 查看 commit 訊息
git log --grep="bug fix"

# 格式化輸出
git log --pretty=format:"%h - %an, %ar : %s"
# %h = 簡短 hash
# %an = 作者名稱
# %ar = 相對時間
# %s = commit 訊息

# 查看檔案變更統計
git log --stat
git log --shortstat

# 查看分支合併圖
git log --graph --oneline --all

git reflog(操作記錄)

reflog = reference log(引用日誌)

記錄 HEAD 的所有移動歷史,包括被刪除的 commit。

# 查看所有操作記錄
git reflog

# 查看最近 10 筆
git reflog -10

# 查看特定分支的 reflog
git reflog show main

# reflog 格式
git reflog --pretty=oneline

log vs reflog 的差異

項目 git log git reflog
記錄內容 Commit 歷史 HEAD 移動歷史
範圍 當前分支的 commit 所有操作(包括已刪除)
保存時間 永久 預設 90 天
用途 查看專案歷史 救回誤刪的 commit
顯示 Commit 訊息和作者 操作動作

範例

# git log 只顯示 commit 歷史
$ git log --oneline
abc123 feat: 新增功能
def456 fix: 修復 bug
ghi789 docs: 更新文件

# git reflog 顯示所有操作
$ git reflog
abc123 HEAD@{0}: commit: feat: 新增功能
def456 HEAD@{1}: commit: fix: 修復 bug
ghi789 HEAD@{2}: reset: moving to HEAD~1    ← reset 操作
xyz000 HEAD@{3}: commit: 被刪除的 commit    ← 可以救回!

救回誤刪的 commit

# 1. 查看 reflog
git reflog

# 2. 找到要救回的 commit(例如 xyz000)
# 3. 恢復
git reset --hard xyz000
# 或建立新分支
git branch recover-branch xyz000

Rebase - 變基

什麼是 Rebase?

將 commit 重新套用到另一個基底上,讓 commit 歷史更線性。

Merge vs Rebase 的差異:

# Merge(產生合併 commit)
main:    A---B---C---M
              \     /
feature:       D---E

# Rebase(線性歷史)
main:    A---B---C---D'---E'

基本 Rebase

# 在 feature 分支上
git rebase main

# 過程:
# 1. 切到 main 的最新 commit
# 2. 將 feature 的 commit 一個個套用上去
# 3. feature 分支現在基於最新的 main

互動式 Rebase

重新整理 commit 歷史(合併、刪除、修改 commit)

# 整理最近 3 個 commit
git rebase -i HEAD~3

# 會開啟編輯器,顯示:
pick abc123 commit 1
pick def456 commit 2
pick ghi789 commit 3

# 可用的指令:
# pick   = 保留這個 commit
# reword = 保留但修改訊息
# edit   = 保留但暫停讓你修改
# squash = 合併到前一個 commit
# fixup  = 合併但丟棄 commit 訊息
# drop   = 刪除這個 commit

範例:合併 commit

# 原本的 commit
pick abc123 feat: 新增登入功能
pick def456 fix: 修正登入 bug
pick ghi789 fix: 再修正登入 bug

# 改成(合併後兩個到第一個)
pick abc123 feat: 新增登入功能
squash def456 fix: 修正登入 bug
squash ghi789 fix: 再修正登入 bug

# 結果:3 個 commit 變成 1 個

Rebase 衝突處理

# 1. Rebase 時遇到衝突
git rebase main
# CONFLICT (content): Merge conflict in file.txt

# 2. 解決衝突
# 編輯 file.txt,移除 <<<<<<< ======= >>>>>>>

# 3. 標記為已解決
git add file.txt

# 4. 繼續 rebase
git rebase --continue

# 如果想放棄 rebase
git rebase --abort

# 跳過當前 commit
git rebase --skip

git rebase --onto(進階變基)

精確控制 rebase 的起點,提取部分 commit 到新基底

最常用方式:提取部分 commit

git rebase --onto <目標分支> <不包含的commit>

意思:把從 <不包含的commit> 之後到當前 HEAD 的所有 commits,搬到 <目標分支>

圖解

原始狀態:
target_branch:  A---B
                     \
current_branch:       C---D---E---F---G  (HEAD)

執行:git rebase --onto target_branch D

結果:
target_branch:  A---B
                     \
                      E'--F'--G'  (HEAD)

說明:
- C 和 D 被拋棄
- E, F, G 移到 target_branch 上
- 省略第三個參數時,預設是當前分支

實際範例

# 情境:清理分支前面不要的 commits

# 查看歷史
git log --oneline
# g7h8i9j (HEAD) feat: 完成新功能
# f6g7h8i feat: 新增測試
# e5f6g7h feat: 實作功能
# d4e5f6g fix: 臨時修改(不要)
# c3d4e5f wip: 開發中(不要)
# b2c3d4e feat: 重要功能
# a1b2c3d (main) Initial commit

# 只要最新的三個 commits,拋棄前面兩個
git rebase --onto main c3d4e5f

# 結果:e5f6g7h, f6g7h8i, g7h8i9j 直接接在 main 上

常見使用場景

  1. 清理分支歷史:拋棄前面不要的實驗性 commits
  2. 修正錯誤的基底:從錯誤的分支點重新開始
  3. 提取最近的工作:只保留最近幾個有用的 commits

完整語法:三個參數

git rebase --onto <新基底> <舊基底> <分支>

意思:將 <分支><舊基底> 之後的 commit 移到 <新基底>

使用場景 1: 改變分支基底

初始:
main:     A---B---C
               \
develop:        D---E
                     \
feature:              F---G
# 將 feature 從 develop 改為基於 main
git rebase --onto main develop feature

# 結果:
main:     A---B---C---F'---G'
               \
develop:        D---E

使用場景 2: 移除中間的 commits

初始:
A---B---C---D---E---F (HEAD)
# 移除 C 和 D,將 E, F 接到 B 上
git rebase --onto B D

# 或使用相對位置
git rebase --onto HEAD~4 HEAD~2

# 結果:
A---B---E'---F' (HEAD)

使用場景 3: 分離分支依賴

初始:
main:       A---B
                 \
feature-B:        C---D
                       \
feature-A:              E---F
# 讓 feature-A 直接基於 main,不依賴 feature-B
git rebase --onto main feature-B feature-A

# 結果:
main:       A---B---E'---F' (feature-A)
                 \
feature-B:        C---D

實用技巧

技巧 1:查看會被移動的 commits

# 先預覽會影響哪些 commit
git log --oneline <舊基底>..HEAD
git log --oneline <舊基底>..<分支>

技巧 2:操作前先備份

# 建立備份分支
git branch feature-backup

# 安心執行 rebase
git rebase --onto main develop feature

# 如果出錯,恢復
git reset --hard feature-backup

技巧 3:使用相對位置

# 移除最近 2 個 commit
git rebase --onto HEAD~2 HEAD

# 移除第 3 和第 4 個 commit
git rebase --onto HEAD~4 HEAD~2

衝突處理

# 執行 rebase
git rebase --onto main develop feature
# CONFLICT (content): Merge conflict in file.txt

# 解決衝突後
git add file.txt
git rebase --continue

# 或放棄整個 rebase
git rebase --abort

常見錯誤

錯誤 1:省略第三個參數時不在正確分支

# ❌ 錯誤:在 main 上執行
git checkout main
git rebase --onto target D
# 會影響 main 分支!

# ✅ 正確:切到要移動的分支
git checkout feature
git rebase --onto target D

錯誤 2:基底順序搞混

# 記憶法:
git rebase --onto <新家> <舊家> <要搬的東西>

# 或更直觀:
git rebase --onto <目標> <不包含的commit> [要搬的分支]

錯誤 3:搞混相對位置方向

# HEAD~2 表示「往前數 2 個」
# 所以 HEAD~4 比 HEAD~2 更舊

git log --oneline
# A (HEAD)
# B (HEAD~1)
# C (HEAD~2)
# D (HEAD~3)
# E (HEAD~4)

# 移除 D 和 C:
git rebase --onto HEAD~4 HEAD~2  # onto E,不包含 C

記憶口訣

# 兩個參數(最常用):
git rebase --onto <新家> <舊鄰居>
→ 把「舊鄰居之後的東西」搬到「新家」

# 三個參數(完整版):
git rebase --onto <新家> <舊家> <要搬的東西>
→ 把「要搬的東西」從「舊家之後」搬到「新家」

與一般 rebase 的對比

# 一般 rebase(簡單)
git rebase main
# → 將當前分支「整個」移到 main 上

# rebase --onto(精確)
git rebase --onto main develop
# → 只移動「develop 之後」的部分到 main 上

Rebase 注意事項

⚠️ 黃金法則:不要 rebase 已經 push 的 commit!

# ❌ 危險(會改變歷史)
git push origin main
git rebase ...             # 修改已 push 的 commit
git push --force           # 強制覆蓋(會影響其他人)

# ✅ 安全(只在本地分支 rebase)
git checkout feature
git rebase main            # 整理本地分支
git push origin feature    # 第一次 push

Reset - 重設

三種模式

git reset 移動 HEAD 到指定的 commit

git reset [模式] <commit>

1. --soft(軟重設)

保留所有變更在暫存區

git reset --soft HEAD~1

效果:
- 撤銷最後一個 commit
- 變更保留在暫存區(staged)
- 可以直接 commit

使用情境:想修改最後一個 commit

git reset --soft HEAD~1
# 修改檔案
git add .
git commit -m "新的 commit 訊息"

2. --mixed(預設)

保留所有變更在工作區(未暫存)

git reset HEAD~1
# 等同於
git reset --mixed HEAD~1

效果:
- 撤銷最後一個 commit
- 變更保留在工作區(unstaged)
- 需要重新 add 才能 commit

使用情境:想重新整理要 commit 的檔案

git reset HEAD~1
# 重新選擇要 commit 的檔案
git add file1.txt
git commit -m "只 commit file1"

3. --hard(硬重設)

完全刪除所有變更

git reset --hard HEAD~1

效果:
- 撤銷最後一個 commit
- 刪除所有變更
- ⚠️ 無法復原(除非用 reflog)

使用情境:確定要放棄所有變更

# 放棄所有本地修改
git reset --hard HEAD

# 回到前 3 個 commit
git reset --hard HEAD~3

Reset 視覺化

初始狀態:
A---B---C (HEAD, main)

git reset --soft HEAD~1
A---B (HEAD, main)
      C 的變更在暫存區 ✅

git reset --mixed HEAD~1  (預設)
A---B (HEAD, main)
      C 的變更在工作區 ✅

git reset --hard HEAD~1
A---B (HEAD, main)
      C 的變更被刪除 ❌

Reset 到特定 Commit

# 使用 commit hash
git reset --hard abc123

# 使用相對位置
git reset --hard HEAD~3    # 回到前 3 個 commit
git reset --hard HEAD^     # 回到上一個 commit

# 重設到遠端狀態
git reset --hard origin/main

救回 Reset 的 Commit

# 1. 查看 reflog
git reflog

# 2. 找到被 reset 前的 commit
abc123 HEAD@{1}: reset: moving to HEAD~1
def456 HEAD@{0}: commit: 被刪除的 commit

# 3. 恢復
git reset --hard def456

Revert - 還原

什麼是 Revert?

建立一個新的 commit 來還原之前的變更(不修改歷史)

原本:
A---B---C (HEAD)

git revert C
A---B---C---C' (HEAD)
       C' 還原 C 的變更

基本用法

# 還原最後一個 commit
git revert HEAD

# 還原特定 commit
git revert abc123

# 還原但不自動 commit
git revert -n abc123
# 或
git revert --no-commit abc123

Revert 多個 Commit

# 還原最近 3 個 commit
git revert HEAD~3..HEAD

# 還原範圍
git revert abc123..def456

Revert 衝突處理

# 1. Revert 時遇到衝突
git revert abc123
# CONFLICT (content): Merge conflict in file.txt

# 2. 解決衝突
# 編輯 file.txt

# 3. 標記為已解決
git add file.txt

# 4. 繼續 revert
git revert --continue

# 放棄 revert
git revert --abort

Reset vs Revert vs Rebase 比較

指令 修改歷史 產生新 commit 適用情境 安全性
reset ✅ 是 ❌ 否 本地分支整理 ⚠️ 危險
revert ❌ 否 ✅ 是 已 push 的變更 ✅ 安全
rebase ✅ 是 ❌ 否* 整理 commit 歷史 ⚠️ 危險

* Rebase 會產生新的 commit hash

使用場景

Reset - 本地整理

# 情境:commit 錯了,還沒 push
git reset --soft HEAD~1    # 保留變更
# 重新 commit

Revert - 已經 Push

# 情境:push 後發現有問題
git revert abc123          # 建立還原 commit
git push origin main       # 安全地 push

Rebase - 整理歷史

# 情境:功能分支要合併前整理
git rebase -i main         # 壓縮、重排 commit
git push origin feature    # 第一次 push

黃金法則

本地 commit:可以用 reset 或 rebase
已 push 的 commit:只能用 revert

原因:reset 和 rebase 會修改歷史
     如果已 push,會影響其他協作者

暫存變更

# 暫存目前變更
git stash
git stash save "說明文字"

# 包含未追蹤的檔案
git stash -u

# 查看 stash 清單
git stash list

# 套用最新的 stash
git stash apply
git stash pop              # 套用並刪除

# 套用特定 stash
git stash apply stash@{2}

# 刪除 stash
git stash drop stash@{0}
git stash clear            # 清空所有 stash

查看差異

# 工作區 vs 暫存區
git diff

# 暫存區 vs 最新 commit
git diff --staged
git diff --cached

# 工作區 vs 特定 commit
git diff HEAD
git diff abc123

# 比較兩個 commit
git diff abc123 def456

# 比較分支
git diff main feature

# 只顯示檔名
git diff --name-only

# 統計變更
git diff --stat

標籤 (Tag)

# 列出標籤
git tag
git tag -l "v1.*"          # 篩選

# 建立標籤
git tag v1.0.0             # 輕量標籤
git tag -a v1.0.0 -m "版本 1.0.0"  # 附註標籤

# 查看標籤資訊
git show v1.0.0

# 推送標籤
git push origin v1.0.0
git push origin --tags     # 推送所有標籤

# 刪除標籤
git tag -d v1.0.0          # 本地刪除
git push origin :refs/tags/v1.0.0  # 遠端刪除
git push origin --delete v1.0.0    # 遠端刪除(新語法)

# Checkout 標籤
git checkout v1.0.0

其他實用指令

# 查看誰修改了哪一行
git blame file.txt
git blame -L 10,20 file.txt  # 指定行數

# 搜尋 commit
git log -S "搜尋字串"     # 搜尋程式碼
git log -G "regex"         # 用正規表達式搜尋

# 查看檔案在某個 commit 的內容
git show abc123:file.txt

# 清理未追蹤的檔案
git clean -n               # 預覽會刪除的檔案
git clean -f               # 刪除未追蹤的檔案
git clean -fd              # 刪除未追蹤的檔案和目錄

# Cherry-pick(挑選特定 commit)
git cherry-pick abc123

# 查看簡短的 commit hash
git rev-parse --short HEAD

# 查看遠端分支的最新 commit
git ls-remote origin

救援指令

# 救回誤刪的檔案(還沒 commit)
git checkout -- file.txt

# 救回已刪除的 commit
git reflog                 # 找到 commit hash
git reset --hard abc123    # 恢復

# 救回已刪除的分支
git reflog                 # 找到分支最後的 commit
git branch recover abc123  # 建立新分支

# 取消 add
git reset file.txt
git restore --staged file.txt  # 新語法

# 取消工作區的修改
git checkout -- file.txt
git restore file.txt       # 新語法

效能與維護

# 垃圾回收
git gc

# 優化 repository
git gc --aggressive

# 檢查 repository 完整性
git fsck

# 清理 reflog
git reflog expire --expire=30.days --all
git gc --prune=now

# 查看 repository 大小
git count-objects -vH

.gitignore 規則

# 註解
# 這是註解

# 忽略特定檔案
secret.txt

# 忽略特定副檔名
*.log
*.tmp

# 忽略目錄
node_modules/
build/

# 例外(不忽略)
!important.log

# 只忽略當前目錄的檔案
/TODO

# 忽略任何目錄下的檔案
**/temp

# 忽略特定目錄下的檔案
doc/*.txt

常用組合指令

# 完整的 log 顯示
git log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit --date=relative

# 可以設為 alias
git config --global alias.lg "log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit --date=relative"

# 使用
git lg

# 顯示所有 unstaged 的變更
git diff --name-only

# 強制同步遠端(覆蓋本地)
git fetch origin
git reset --hard origin/main

# 刪除已合併的分支
git branch --merged | grep -v "\*" | xargs -n 1 git branch -d

實戰範例

範例 1:完整開發流程

# 1. 建立新分支
git checkout -b feature/new-feature

# 2. 開發並提交
git add .
git commit -m "feat: add new feature"

# 3. Push 到遠端
git push -u origin feature/new-feature

# 4. 合併到 main
git checkout main
git merge feature/new-feature
git push origin main

範例 2:修復錯誤提交

# 情境:commit 錯了,還沒 push
git reset --soft HEAD~1    # 保留變更
# 重新 commit

# 情境:已經 push
git revert HEAD           # 建立還原 commit
git push origin main

範例 3:同步遠端變更

# 方法 1:merge
git pull origin main

# 方法 2:rebase(保持線性歷史)
git pull --rebase origin main

最佳實踐

1. 分支策略

推薦

  • 使用 feature branches 開發
  • main/master 保持穩定
  • 定期同步遠端變更

避免

  • 直接在 main 上開發
  • 長期不合併的分支

2. Commit 訊息

推薦

feat: add user authentication
fix: resolve login timeout issue
docs: update README with setup instructions

避免

update
fix
changes

3. Rebase 使用

安全

  • 本地分支可以 rebase
  • 整理未 push 的 commits

危險

  • 不要 rebase 已 push 的 commits
  • 會影響協作者

常見問題

問題 1:如何撤銷已經 push 的 commit?

# 使用 revert(推薦)
git revert <commit-hash>
git push origin main

問題 2:如何合併多個 commits?

# 使用互動式 rebase
git rebase -i HEAD~3
# 將 pick 改為 squash

問題 3:如何救回誤刪的 commits?

# 1. 查看 reflog
git reflog

# 2. 找到 commit hash
# 3. 恢復
git reset --hard <commit-hash>

問題 4:如何解決合併衝突?

# 1. 查看衝突檔案
git status

# 2. 編輯檔案解決衝突
# 移除 <<<<<<< ======= >>>>>>>

# 3. 標記為已解決
git add <file>

# 4. 完成合併
git commit

總結

快速參考

檔案狀態流程

工作區 → 暫存區 → Repository → Remote

未追蹤 → git add → 已暫存 → git commit → 已提交 → git push → 遠端
(Untracked) (Staged) (Committed) (Pushed)

HEAD 指標

HEAD        當前 commit
HEAD~1      上一個 commit
HEAD~2      上上個 commit
HEAD^       上一個 commit(等於 HEAD~1)
HEAD^^      上上個 commit(等於 HEAD~2)

撤銷操作速查

情況 指令
取消工作區修改 git restore file.txt
取消暫存 git restore --staged file.txt
修改最後的 commit git commit --amend
撤銷 commit(保留變更) git reset --soft HEAD~1
撤銷 commit(刪除變更) git reset --hard HEAD~1
還原已 push 的 commit git revert abc123
放棄所有本地變更 git reset --hard HEAD

核心要點

  1. Git 工作流程

    • 工作區 → 暫存區 → Repository → Remote
    • 使用 feature branches 開發
    • 定期同步和提交
  2. 常用指令組合

    • git add . && git commit -m "message" && git push
    • git pull --rebase && git push
    • git stash && git pull && git stash pop
  3. 安全原則

    • 本地 commit 可以 reset/rebase
    • 已 push 的 commit 只能 revert
    • 定期備份重要分支
  4. 最佳工具

    • 使用 alias 提升效率
    • 善用 reflog 救援誤操作
    • 定期 git gc 清理

建立日期:2025-10-28 最後更新:2025-11-18

🔗相關文章