[筆記] Git 常用命令大全(按場景分類)

[筆記] Git 常用命令大全(按場景分類)

適用於日常開發中對 Git 的常見操作。透過分類整理,幫助你快速上手或查閱。


📦 基礎指令

指令

用途

git init

初始化一個 Git 儲存庫(建立 .git 資料夾)。

git clone <url>

將遠端儲存庫複製到本地。

git status

查看目前工作目錄狀態(檔案修改、暫存等)。

git add <file>

將檔案新增到暫存區。

git commit -m "message"

提交暫存區檔案到本地儲存庫,並新增提交訊息。

git log

查看提交歷史。


🌱 分支管理

指令

用途

git branch

查看本地分支列表。

git branch <branch-name>

建立一個新分支。

git checkout <branch-name>

切換到指定分支。

git switch <branch-name>

切換到指定分支(推薦使用的新指令)。

git merge <branch-name>

將指定分支合併到目前分支。

git branch -d <branch-name>

刪除已合併的分支。

git branch -D <branch-name>

強制刪除分支。


🌍 遠端儲存庫操作

指令

用途

git remote -v

查看遠端儲存庫位址。

git remote add <name> <url>

新增遠端儲存庫。

git pull

從遠端儲存庫拉取程式碼並合併。

git push

將目前分支程式碼推送到遠端儲存庫。

git push -u origin <branch-name>

推送分支並設定上游(追蹤)分支。

git fetch

取得遠端儲存庫最新資料,但不自動合併。

git remote remove <name>

刪除遠端儲存庫連線。


🔍 查看與對比

指令

用途

git diff

查看工作區未暫存的變更。

git diff --staged

查看暫存區的變更。

git log --oneline

簡潔地查看提交歷史。

git show <commit-id>

查看某次提交的詳細資訊。

git blame <file>

查看檔案每行對應的提交記錄。


♻️ 撤銷與回溯

指令

用途

git checkout -- <file>

撤銷對工作區檔案的修改。

git restore <file>

撤銷檔案修改(新指令)。

git reset HEAD <file>

將檔案從暫存區移回工作區。

git reset --soft <commit-id>

回溯到某次提交,保留所有改動。

git reset --mixed <commit-id>

回溯並清除暫存區,但保留工作區改動。

git reset --hard <commit-id>

回溯並清除所有改動。

git revert <commit-id>

產生一個新提交,撤銷某次提交內容。


🏷️ 標籤管理

指令

用途

git tag

查看所有標籤。

git tag <tag-name>

建立標籤。

git tag -d <tag-name>

刪除標籤。

git push origin <tag-name>

推送指定標籤。

git push origin --tags

推送所有標籤到遠端。


🗃️ Stash(暫時儲存)

指令

用途

git stash

暫存目前未提交的修改。

git stash list

查看所有暫存記錄。

git stash apply

恢復最近一次 stash 內容。

git stash drop

刪除最近一次 stash。

git stash pop

恢復並刪除最近一次 stash。


🛠️ 其他實用指令

指令

用途

git config --global user.name "Your Name"

設定全域使用者名稱。

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

設定全域電子郵件。

git config --list

查看目前 Git 配置。

git clean -f

刪除未被追蹤的檔案。

git cherry-pick <commit-id>

將某個提交應用到目前分支。

git rebase <branch>

目前分支變基到目標分支之上。


🧪 常用分支操作範例

# 拉取 PR 分支程式碼(如 GitHub Pull Request)
git fetch origin pull/376/head:pr-review

# 切換到測試分支
git checkout pr-review

# 切換回主分支
git checkout main

# 合併測試分支
git merge pr-review

# 合併為一條提交
git merge --squash pr-review
git commit -m "合併所有變更"

# 回溯到某個提交
git reset --hard <commit-id>

# 刪除本地分支
git branch -d pr-review

# 強制刪除本地分支
git branch -D pr-review

# 刪除遠端分支
git push origin --delete <branch-name>

# 清理遠端分支快取
git fetch -p

# 強制覆蓋遠端分支
git push origin main --force

📚 延伸閱讀


如果你經常使用 Git,不妨收藏這篇文章,以備查閱!也歡迎留言補充你常用的 Git 技巧。

Powered by ❤️ with Hugo and Stack Theme.