目錄

Git 常用指令跟設定

基礎概念

  1. Working directory: 工作目錄

  2. Staging area: 暫存區

  3. remote and origin: remote 指的是遠端的 repo,概念,origin 是真的一個指標指向一個 url

    $ git remote -v
    origin  https://github.com/example/repo.git (fetch)
    origin  https://github.com/example/repo.git (push)
  4. HEAD: 指向現在整個工作環境所在的 commit

  5. Branch: 只是指標,所以切換 branch 就是把 HEAD 指標移動到 MASTER 指標上

Config

[user]
    email = bses30074@gmail.com
    name = Yan-Hao-Wang
[core]
    editor = vim
    autocrlf = input
[color]
    ui = true
[diff]
    algorithm = histogram
    indentHeuristic = true
[branch]
    sort = -committerdate
[pull]
    rebase = true
[alias]
    st = status
    rst = restore
    ck = checkout
    lg = log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit
  • autocrlf = input: 在送出(Commit)時自動將 CRLF 轉為 LF,但在拉取(Checkout)時不做變動
  • ui = true: 強制在終端機顯示顏色,讓 status 或 diff 的結果一眼就能看出哪些是新增或刪除
  • algorithm = histogram: 比起預設的 myers,histogram 能更聰明地處理程式碼塊的搬移,產生的 diff 邏輯更貼近人類閱讀程式碼的方式
  • indentHeuristic = true: 當你移動函數或修改巢狀縮排時,Git 會試著讓 diff 的起點和終點對齊縮排,讓修改看起來更整潔
  • sort = -committerdate: 當你執行 git branch 時,它會把最近操作過的分支排在最上面
  • rebase = true 執行 git pull 時預設用 rebase 而不是 merge
  • lg = ...: 它會用漂亮的顏色與線條畫出分支拓撲圖,並顯示相對時間(如 2 hours ago)與作者

常用指令速查表

分類 指令 功能說明 備註
暫存與提交 (Add/Commit) git add -p 互動式暫存已追蹤檔案的部分區塊 適合將一個檔案拆成多個 commit
git commit --amend 將目前的修改併入上一次 commit 常用於修正 commit 訊息或補檔
還原 (Restore) git restore <file> 將工作目錄檔案還原至 HEAD 狀態 取代舊版 git checkout <file>
git restore --staged <file> 將檔案從暫存區移回工作目錄 讓檔案變成「已修改但未暫存」
git restore --source HEAD~2 <f> 將特定檔案還原至前兩個版本的狀態 只針對單一檔案進行時光倒流
重置 (Reset) git reset --soft HEAD~1 退回版本,保留暫存區與工作目錄修改 適合重新組合多個 commit
git reset --mixed HEAD~1 退回版本,重置暫存區,保留工作目錄 Git 的預設重置模式
git reset --hard HEAD~1 退回版本,刪除所有未提交的修改 危險:所有更動都會消失
日誌與差異 (Log/Diff) git log --oneline <file> 以單行模式顯示特定檔案的 commit 紀錄 快速追蹤該檔案的歷史
git diff --staged 比較「暫存區」與「最後一次提交」差異 確認準備要 commit 的內容
git diff --color-words 顯示單字級差異,不顯示 +/- 符號 適合需要複製乾淨程式碼時使用
git diff -U1000 顯示前後各 1000 行的上下文 適合 Review 較長的函數邏輯
分支 (Branch/Checkout) git checkout -b <name> 建立新分支並立即切換過去 常用於開發新 Feature
git branch -m <new_name> 修改當前分支的名稱
git branch -vv 查看本地分支與遠端分支的追蹤關係 確認 Upstream 設定是否正確
git branch -D <branch> 強制刪除分支(不論是否已合併)
合併與重底 (Merge/Rebase) git merge <branch> --no-ff 合併時強制產生一個 Merge Commit 保留完整的分支開發軌跡
git rebase <new_base> 將當前分支的基準點移動到 new_base 維持線性歷史,線圖更整潔
git rebase -i HEAD~n 互動式 Rebase,編輯最近 n 個 commit 可進行 squash (合併) 或 edit
遠端 (Remote/Push) git push <rem> <b1>:<b2> 本地 b1 推送到遠端並命名為 b2 手動指定遠端分支名稱
git push <rem> :<branch> 刪除指定的遠端分支 冒號前留白代表「推入空內容」
git branch --set-upstream-to=<u> 設定本地分支追蹤特定的遠端分支 例如:origin/main
暫存 (Stash) git stash pop 取出最新的暫存進度並從清單中移除 處理臨時需要切換分支的情況
git stash list 列出目前所有暫存的進度
git stash push -m "Messages..." 存入時加上訊息 (Message)
git stash apply stash@{x} 套用某個暫存,但不刪除
git stash show stash@{x} 查看特定 Index 的檔案清單
git stash show -p stash@{x} 查看特定 Index 的程式碼差異
git stash drop stash@{x} 刪除特定 Index 的暫存
特殊 git mv 可被 Git 識別的移動檔案

Reference