Git 最容易出錯的地方不是指令背不熟,而是不知道目前在哪個分支、哪些檔案已 staged、操作會不會改寫共用歷史。養成每一步前後看 git status 與 git diff 的習慣。
建立與查看版本庫
複製遠端版本庫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 或系統內建說明確認,再以當版官方文件為準。