Git 問題大全筆記:工作常用指令與實務操作範例

4/16/2025 Git

# 還原 / 誤刪 Commit 的復原

# 🧩 如何還原被 reset 掉的 commit?

git reflog
git cherry-pick <commit-hash>

🔍 案例:誤用了 git reset HEAD~2,導致兩筆 commit 被刪,可用 reflog 查回,再用 cherry-pick 撈回來。


# Commit 操作補救與修改

# 📌 某個檔案忘記跟著 commit(已經過了幾個 commit)

# 修改後補一筆 commit
git add <filename>
git commit -m "補上漏掉的檔案"

# 或使用 rebase 編輯歷史
git rebase -i HEAD~3
# 將想加入檔案的那筆改為 edit,再 commit --amend

# ✏️ 修改舊的某筆 commit 訊息

git rebase -i HEAD~3
# 將要修改訊息的 commit 改為 `reword`

# 📎 修改倒數第 3 筆 commit 的內容或訊息

git rebase -i HEAD~3
# 改 pick 為 edit 或 reword

# 切換分支

# 🔁 切換遠端 / 本地分支

git checkout <branch-name>
git checkout -b <local-branch> origin/<remote-branch>

# Pull / Merge 差異比較與合併技巧

# 🔍 比較目前分支與主分支差異

# 顯示誰超前幾筆 commit
git fetch origin
git rev-list --left-right --count origin/main...HEAD

# 📂 只 merge 某個檔案

git checkout other-branch -- path/to/file

# ⚠️ Merge conflict 時一次接受 incoming

git checkout --theirs .

# ✅ 合併分支

git checkout main
git merge feature-x

# Stash 用法

# 📥 把所有變更含「新增檔案」一起 stash

git stash -u

# 📋 查看 stash 的內容

git stash list
git stash show -p stash@{0}

# Git 設定與使用者設定

# 🛠️ 查看 / 設定 user.name 和 email

git config user.name "小安"
git config user.email "you@example.com"

# 🌍 不同裝置可用相同 email + 不同名稱

只要每台機器上設定各自的 user.name 即可。

# 📁 讓某個檔案僅在本機 ignore(不加入 .gitignore)

# 手動在 .git/info/exclude 加入檔案路徑
your-local-config.env

# 進階觀念:空 Commit、Commit Tree、git commit-tree

# ⭕ 建立一個空的 commit

git commit --allow-empty -m "觸發 CI/CD 用"

# 🌲 查看 Commit Tree(圖形化)

git log --oneline --graph --decorate --all

# 🔧 git commit-tree 是什麼?

用來手動建立一棵 commit tree 結構(較進階用途,如腳本、Git plumbing),平常很少用,需配合 git write-tree

最後更新: 7/24/2025, 8:50:37 AM