
Git 備忘錄
開始使用
初始化新儲存庫 (Repo)
git init
複製現有儲存庫
git clone <url>
準備提交 (Commit)
加入未追蹤的檔案或未暫存的變更
git add <file>
加入所有未追蹤的檔案與未暫存的變更
git add .
選擇性暫存檔案中的部分變更
git add -p
移動檔案
git mv <old> <new>
刪除檔案
git rm <file>
從 Git 追蹤中移除檔案但不刪除實體檔案
git rm --cached <file>
取消暫存單一檔案
git reset <file>
取消暫存所有變更
git reset
檢查已加入的項目
git status
進行提交
進行提交(並開啟文字編輯器撰寫提交訊息)
git commit
進行提交
git commit -m 'message'
提交所有未暫存的變更
git commit -am 'message'
在分支間切換
切換分支
git switch <name> 或 git checkout <name>建立分支
git switch -c <name> 或 git checkout -b <name>列出分支
git branch
依最近提交時間列出分支
git branch --sort=-committerdate
刪除分支
git branch -d <name>
強制刪除分支
git branch -D <name>
比對暫存與未暫存的變更
比對所有已暫存與未暫存的變更
git diff HEAD
僅比對已暫存的變更
git diff --staged
僅比對未暫存的變更
git diff
比對提交紀錄
顯示某次提交與其前一次提交的差異
git show <commit>
比對兩次提交
git diff <commit> <commit>
比對某次提交後的檔案變更
git diff <commit> <file>
顯示差異摘要
git diff <commit> --stat git show <commit> --stat指定提交紀錄的方式
當我們提到 <commit> 時,你可以使用以下任何一種格式:
- 分支名稱
- main
- 標籤 (Tag)
- v0.1
- 提交 ID
- 3e887ab
- 遠端分支
- origin/main
- 當前提交
- HEAD
- 3 次提交之前
- HEAD^^^ 或 HEAD~3
捨棄你的變更
刪除單一檔案的未暫存變更
git restore <file> 或 git checkout <file>刪除單一檔案的所有已暫存與未暫存變更
git restore --staged --worktree <file> 或 git checkout HEAD <file>刪除所有已暫存與未暫存的變更
git reset --hard
刪除未追蹤的檔案
git clean
「暫存 (Stash)」所有已暫存與未暫存的變更
git stash
編輯歷史紀錄
「復原」最近的一次提交(保留工作目錄中的變更)
git reset HEAD^
將最後 5 次提交合併為 1 次
git rebase -i HEAD~6
接著將你想與前一個提交合併的項目的 "pick" 改為 "fixup"
復原失敗的變基 (Rebase)
git reflog BRANCHNAME
手動在 reflog 中找到正確的提交 ID,然後執行
git reset --hard <commit>
修改提交訊息(或加入遺漏的檔案)
git commit --amend
程式碼考古 (查詢歷史)
檢視分支的歷史紀錄
git log main git log --graph main git log --oneline顯示修改過該檔案的所有提交
git log <file>
顯示修改過該檔案的所有提交(包含重新命名之前)
git log --follow <file>
搜尋新增或刪除特定文字的所有提交
git log -G banana
顯示檔案中每一行最後是由誰修改的
git blame <file>
合併分歧的分支
使用 Rebase 合併
git switch banana git rebase main
使用 Merge 合併
git switch main git merge banana
使用 Squash Merge 合併
git switch main git merge --squash banana git commit
將一個分支同步到最新進度(又稱「快轉合併」(fast-forward merge))
git switch main git merge banana
複製一個提交到當前分支
git cherry-pick <commit>
還原舊檔案
取得另一個提交中某個檔案的版本
git checkout <commit> <file> 或 git restore <file> --source <commit>新增遠端倉庫 (Remote)
git remote add <name> <url>
推送 (Push) 你的變更
將 main 分支推送到遠端 origin
git push origin main
將當前分支推送到其對應的遠端「追蹤分支」
git push
推送一個從未推送過的分支
git push -u origin <name>
強制推送
git push --force-with-lease
推送標籤 (Tags)
git push --tags
拉取 (Pull) 變更
抓取變更 (Fetch)(但不更動你本地的任何分支)
git fetch origin main
抓取變更後對當前分支進行變基 (Rebase)
git pull --rebase
抓取變更後合併到當前分支
git pull origin main 或 git pull設定 Git
設定組態選項
git config user.name 'Your Name'
全域設定
git config --global ...
新增別名 (Alias)
git config alias.st status
檢視所有可能的組態選項
man git-config
重要檔案
本地 Git 設定檔
.git/config
全域 Git 設定檔
~/.gitconfig
忽略檔案清單
.gitignore