技術文章 · IT 指令工具箱

Git 常用指令:分支、提交、合併、還原、Stash 與遠端

Git 指令怎麼用?整理 clone、status、add、commit、switch、merge、rebase、restore、revert、stash、fetch、pull 與 push 的安全用法。

作者 Steve Chen · 發布  · 約 5 分鐘閱讀

IT 指令工具箱 — 廷皓技術專欄插圖

Git 最容易出錯的地方不是指令背不熟,而是不知道目前在哪個分支、哪些檔案已 staged、操作會不會改寫共用歷史。養成每一步前後看 git status 與 git diff 的習慣。

27 組範例GitGitHub/GitLab/自架 Git查核日期:2026-08-11
動手前:不要把密碼、API key、私鑰或個資提交進版本庫;刪掉工作目錄檔案不代表秘密已離開歷史。共用分支避免 force push 與未協調的 history rewrite。

建立與查看版本庫

複製遠端版本庫Git

git clone https://github.com/example/project.git

確認網址與預期儲存位置。

複製到指定資料夾Git

git clone https://github.com/example/project.git project-local

目的資料夾最好尚未存在或為空。

查看目前狀態Git

git status --short --branch

同時看到分支、staged、modified 與 untracked。

查看提交紀錄Git

git log --oneline --decorate --graph -20

圖形化顯示最近 20 筆與分支指標。

查看遠端Git

git remote -v

確認 fetch 與 push 目標沒有指錯環境。

查看目前設定來源Git

git config --list --show-origin

可辨認 system、global 與 local 哪層生效。

設定單一 repo 使用者Git

git config user.name "Your Name" && git config user.email "[email protected]"

不加 --global,只套用目前版本庫。

檢查、暫存與提交

查看尚未 staged 的差異Git

git diff

提交前先確認沒有 debug、token 或非預期格式化。

查看已 staged 差異Git

git diff --staged

這才是下一次 commit 真正會收進去的內容。

加入指定檔案Git

git add src/app.py tests/test_app.py

比 git add . 更容易控制範圍。

逐段選擇要加入的變更Git

git add -p

可把同一檔案拆成多個清楚的 commit。

建立提交Git

git commit -m "fix: handle API timeout"

訊息寫清楚做了什麼與原因。

查看單一提交Git

git show --stat --oneline HEAD

先看摘要;需要時再看完整 diff。

把檔案移出 stagedGit

git restore --staged config/local.env

保留工作目錄修改,只取消 staged。

放棄單一檔案未提交修改Git

git restore src/app.py

工作目錄變更會消失,先用 git diff 確認。

分支、同步與還原

列出本機與遠端分支Git

git branch --all --verbose

先辨認 upstream 與最後提交。

建立並切換分支Git

git switch -c feature/device-search

分支名稱用團隊約定。

切回既有分支Git

git switch main

若有衝突中的操作或未保存變更,Git 可能阻止切換。

只抓遠端狀態Git

git fetch --prune

不會自動合併;--prune 移除已不存在的 remote-tracking branch。

查看本機與遠端差異Git

git log --oneline HEAD..origin/main

顯示遠端 main 有、本機目前沒有的提交。

以 fast-forward 更新Git

git pull --ff-only

若需要產生 merge commit 會停止,避免意外歷史形狀。

合併指定分支Git

git merge --no-ff feature/device-search

先更新並測試目標分支;團隊若用 squash 流程依規範調整。

暫存目前工作Git

git stash push -u -m "WIP before hotfix"

-u 包含 untracked,但不含 ignored 檔。

查看 stashGit

git stash list

套回前用 git stash show -p 檢查。

套回但保留 stashGit

git stash apply stash@{0}

apply 成功後不會自動刪除,可確認無誤再 drop。

建立反向提交Git

git revert <commit-id>

適合已推到共用分支的錯誤提交,不改寫歷史。

推送並設定 upstreamGit

git push -u origin feature/device-search

第一次推新分支常用;確認遠端名稱。

怎麼確認有做對

  • commit 前看 git diff --staged,push 前看 git log 與 git status。
  • 合併後跑測試、lint 與建置,不只看衝突是否解完。
  • 還原正式問題優先用 revert,並確認反向提交實際部署結果。

常見錯誤

  • 用 git add . 把秘密或暫存檔一起提交。
  • 在共用 main 直接 rebase 或 force push。
  • 用 reset --hard 當一般復原手段。
  • 只解掉文字衝突,沒有測業務行為。

版本與官方文件

參數會隨工具版本與作業系統實作改變。正式環境先用 --help、-h 或系統內建說明確認,再以當版官方文件為準。

聯絡廷皓討論 看更多文章