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 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

捨棄你的變更

刪除單一檔案的未暫存變更

git restore <file> git checkout <file>

刪除單一檔案的所有已暫存與未暫存變更

git restore --staged --worktree <file> git checkout HEAD <file>

刪除所有已暫存與未暫存的變更

git reset --hard

刪除未追蹤的檔案

git clean

「暫存 (Stash)」所有已暫存與未暫存的變更

git stash

程式碼考古 (查詢歷史)

檢視分支的歷史紀錄

git log main git log --graph main git log --oneline

顯示修改過該檔案的所有提交

git log <file>

顯示修改過該檔案的所有提交(包含重新命名之前)

git log --follow <file>

搜尋新增或刪除特定文字的所有提交

git log -G banana

顯示檔案中每一行最後是由誰修改的

git blame <file>

還原舊檔案

取得另一個提交中某個檔案的版本

git checkout <commit> <file> git restore <file> --source <commit>

新增遠端倉庫 (Remote)

git remote add <name> <url>

拉取 (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