Git 命令速查
日常高頻 Git 命令快速參考:init、clone、branch、merge、rebase、reset、stash、遠端操作、歷史查詢,並附帶常用參數與實作範例。
31 條命令
入門
git init在當前目錄建立一個新的 Git 倉庫。
git init my-projectgit clone <url>將遠端倉庫複製到本地,包含完整歷史記錄。
--depth 1 淺克隆(只含最新提交);-b <branch> 克隆指定分支
git clone -b main --depth 1 https://github.com/user/repo.gitgit config設定使用者名稱、電郵等配置;--global 對所有倉庫生效。
git config --global user.name "Your Name" && git config --global user.email "[email protected]"日常操作
git status檢視工作區狀態:已修改、已暫存、未追蹤的檔案。
-s 簡短格式;-b 顯示分支資訊
git status -sbgit add <file>將檔案變更加入暫存區,為下一次提交做準備。
-A 暫存所有變更;-p 互動挑選區塊;-u 僅暫存已被追蹤的檔案
git add -p src/index.tsgit commit將暫存的變更記錄為一次提交。
-m 提交訊息;-a 暫存被追蹤檔案並提交;--amend 改寫上一次提交
git commit -am "fix: 處理空輸入"git diff顯示工作區、暫存區、各提交之間的行級差異。
--staged 與上次提交的差異;<branch> 與某分支的差異;--stat 只顯示摘要
git diff --staged --statgit restore <file>捨棄工作區未提交的修改(加 --staged 可取消暫存)。
git restore --staged src/index.ts分支
git branch列出、建立或刪除分支。
-d 刪除;-D 強制刪除;-m 重新命名;-a 同時列出遠端分支
git branch -m old-name new-namegit switch <branch>切換到其他分支;-c 會先建立分支再切換(取代舊的 checkout)。
git switch -c feature/logingit merge <branch>將其他分支合併到當前分支。
--no-ff 總是產生合併提交;--abort 取消正在進行的合併
git merge --no-ff feature/logingit rebase <branch>將當前分支的提交「重播」到另一個分支頂端,得到線性歷史。
-i 互動式(合併/改寫/重排);--abort 取消;--continue 解決後繼續
git rebase -i HEAD~3遠端
git remote -v列出已設定的遠端倉庫及其網址。
git remote add origin https://github.com/user/repo.gitgit fetch從遠端下載物件與參考,但不自動合併。
--prune 刪除過時的遠端追蹤分支;--all 取得所有遠端
git fetch --prune origingit pull從遠端取得並合併(或 rebase)到當前分支。
--rebase 改用 rebase;--ff-only 僅快進合併
git pull --rebase origin maingit push將本地提交推送到遠端倉庫。
-u 設定上游追蹤;--force-with-lease 更安全的強推;--tags 推送標籤
git push -u origin feature/login還原與修復
git reset把 HEAD 移到其他提交,可選擇同時修改暫存區與工作區。
--soft 保留變更在暫存區;--mixed(預設)保留在工作區;--hard 捨棄所有變更
git reset --hard HEAD~1git revert <commit>產生新提交來還原之前的某次提交,對共享歷史而言是安全的。
git revert HEADgit commit --amend改寫最近一次提交:補上漏掉的檔案或修改提交訊息。
--no-edit 保留原提交訊息
git commit --amend --no-editgit clean刪除工作區中未追蹤的檔案。
-n 預覽;-f 強制;-d 包含目錄;-x 包含被忽略的檔案
git clean -ndx歷史與查看
git log顯示提交歷史。
--oneline 每條一行;--graph 分支圖;-p 顯示差異;-n 限制筆數
git log --oneline --graph -15git show <commit>顯示某次提交的說明與差異;也可用於標籤或檔案(git show HEAD:file)。
git show HEAD~2 --statgit blame <file>逐行列出該行最後修改者與對應提交。
-L n,m 僅顯示指定行範圍
git blame -L 10,20 src/index.tsgit reflog顯示 HEAD 的移動歷史——可在 reset/rebase 出錯時找回「遺失」的提交。
git reflog -20暫存
git stash暫時擱置未提交的修改,讓工作區恢復乾淨。
-u 包含未追蹤檔案;push -m 說明;list 列出所有 stash
git stash push -u -m "wip: 登入表單"git stash pop還原最近的 stash 並從 stash 列表移除。
apply 還原但保留 stash 條目
git stash apply stash@{1}標籤與發佈
git tag列出、建立或刪除標示發佈點的標籤。
-a 註解標籤;-m 說明;-d 刪除
git tag -a v1.2.0 -m "Release 1.2.0"git describe --tags顯示當前提交可達的最近標籤及距離。
git describe --tags --always進階
git cherry-pick <commit>將指定提交的變更套用到當前分支。
-n 套用但不提交;-x 在提交訊息中附加來源提交哈希
git cherry-pick -x a1b2c3dgit bisect用二分搜尋找出引入 bug 的提交。
start / bad / good / run <cmd> / reset
git bisect start && git bisect bad && git bisect good v1.0.0git worktree add <path> <branch>在同一個倉庫下,於獨立目錄簽出其他分支。
git worktree add ../hotfix hotfix/urgent-bug速查頁版本 1.0.0
適用於 Git 2.30+