Git:.gitignore、移除暫存與撤銷修改
1. .gitignore常見項目添加
1.1 .gitignore模板
.gitignore針對每個語言都有對應的模板,在GitHub創建項目時就可以選擇(你可以在GitHub提供的.gitignore模板大全中找到它)。如Python語言的.gitignore模板如下:
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
pip-wheel-metadata/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
.python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
1.2 添加更多的.gitignore項目
但是這些往往是不夠的的。如我們在Mac系統下用VSCode開發,那么常常還需要添加以下項目:
# IDE - VSCode
.vscode/
# OS generated files
.DS_Store
其中.vscode/表示忽略.vscode這個包含項目配置文件的隱藏目錄(注意是包括目錄一起忽略,這個和Linux下諸如cp test/ .這類命令的語義有區別,參加我的博客《Linux:文件解壓、復制和移動的若干坑》),.DS_Store表示忽略掉Mac操作系統下存儲目錄自定義屬性的隱藏文件。
此外,我們再以機器學習相關的項目為例子,數據(放在data目錄下)和模型(放在model目錄下)通常異常巨大,我們并不想將它們放到項目文件夾下,因此我們可能傾向于添加如下的項目:
# data files
data/*
# model files
model/*
data/*和model/*語義上表示忽視data目錄下所有文件與model目錄下所有文件及子目錄(不包括data和model目錄本身)。但是我們會發現,實際上空的data和model目錄并沒有成功git add到項目中:
(base) orion-orion@MacBook-Pro Learn-Git % git add data
(base) orion-orion@MacBook-Pro Learn-Git % git add model
(base) orion-orion@MacBook-Pro Learn-Git % git status
On branch main
Your branch is ahead of 'origin/main' by 1 commit.
(use "git push" to publish your local commits)
nothing to commit, working tree clean
這是因為空目錄不會稱為Git版本控制系統跟蹤(track)。但是如果我們想保存data和model的目錄架構呢?很簡單,我們只需要在data和model目錄下添加.gitkeep目錄即可,然后將在.gitignore文件中對.gitkeep進行反選(即不忽視):
# data files
data/*
!data/.gitkeep
# model files
model/*
!model/.gitkeep
可以看到由于隱藏文件的存在,現在空目錄能夠正常git add了:
(base) orion-orion@MacBook-Pro Learn-Git % git add data
(base) orion-orion@MacBook-Pro Learn-Git % git add model
(base) orion-orion@MacBook-Pro Learn-Git % git status
On branch main
Your branch is ahead of 'origin/main' by 1 commit.
(use "git push" to publish your local commits)
Changes to be committed:
(use "git restore --staged <file>..." to unstage)
new file: data/.gitkeep
new file: model/.gitkeep
但是需要注意,如果這樣寫就沒用:
# data files
data/
!data/.gitkeep
因為data/表示將data目錄本身也忽略了,Git根本就不會去查看該目錄,以致.gitkeep文件也就不起作用了。
額外提一下,如果我們僅僅希望忽略掉data目錄下的.csv文件,可以這樣寫:
# data files
data/*.csv
2. 移除已暫存(staged)的文件
2.1 關于跟蹤與暫存
在Git中,一個文件可能在這三種區域中:工作目錄(Working Directory),暫存區(Staging Area,也稱索引index),Git倉庫(可視為一棵提交樹committed tree)。三者關系如下圖所示:

當我們將文件添加到項目目錄中時,我們其實是在將其添加到工作目錄中。
一旦一個目錄或文件被git add了一次,那么它就會被跟蹤(track)并加入暫存區。此后再對其進行修改,Git會提醒你Changes not staged for commit與modified: README.md,需要再次運行git add將其暫存(staged):
(base) orion-orion@MacBook-Pro Learn-Git % echo "new version" > README.md
(base) orion-orion@MacBook-Pro Learn-Git % git status
On branch main
Your branch is ahead of 'origin/main' by 2 commits.
(use "git push" to publish your local commits)
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git restore <file>..." to discard changes in working directory)
modified: README.md
no changes added to commit (use "git add" and/or "git commit -a")
而文件的所謂的未跟蹤(untracked)、未修改(unmodified)、已修改(modified)、已暫存(staged)四種狀態的關系如下所示:
2.2 清除已暫存的文件
現在假設我們搞忘了編寫.gitignore,然后已經用了git add -A或git add .命令目錄下所有文件及子目錄都暫存了(在Git 2.0中git add -A或git add .命令等效)。而其中有很大的日志文件或一些諸如*.a的編譯文件,我們如何將這些文件從暫存區域移除以取消跟蹤呢?可以用git rm --cached命令完成此項工作,如:
git rm --cached README.md
注意要帶上選項--cached,而不僅僅是git rm,git rm除了從暫存區域移除外,還會將磁盤上的文件也一起刪了。關于參數選項可以參見我的博客《Linux:可執行程序的Shell傳參格式規范 》。
使用該命令效果如下:
(base) orion-orion@MacBook-Pro Learn-Git % git rm --cached README.md
rm 'README.md'
(base) orion-orion@MacBook-Pro Learn-Git % git status
On branch main
Your branch is ahead of 'origin/main' by 2 commits.
(use "git push" to publish your local commits)
Changes to be committed:
(use "git restore --staged <file>..." to unstage)
deleted: README.md
注意到Changes to be committed:與deleted: README.md,這說明當我們使用git rm --cached并commit后, 相關的文件還會被從committed tree中移除。如果我們只想移除出暫存區,可以使用下列命令:
git reset HEAD README.md
該命令等同 git reset --mixed HEAD README.md(默認參數為--mixed,它還可選的參數包括soft和--hard,我們放在3.3節講)。使用后效果如下:
(base) orion-orion@MacBook-Pro Learn-Git % git reset HEAD *.md
Unstaged changes after reset:
M README.md
(base) orion-orion@MacBook-Pro Learn-Git % git status
On branch main
Your branch is ahead of 'origin/main' by 2 commits.
(use "git push" to publish your local commits)
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git restore <file>..." to discard changes in working directory)
modified: README.md
no changes added to commit (use "git add" and/or "git commit -a")
注意到Changes not staged for commit:與 modified: README.md。說明該命令只是將README.md移除暫存區,但是上次對README.md的commit還在(即撤銷最近的一次commit之后的變化)。
如果要遞歸地將當前目錄下的所有文件及子目錄移除出暫存區(與commit tree),可以這樣寫:
git rm -r --cached .
注意這個命令非常危險和暴力,一般還是建議指定具體的目錄或文件名。
3. 追加與撤銷git commit操作
3.1 commit歷史查看
用git log命令可以看到項目的git commit歷史:
(base) orion-orion@MacBook-Pro Learn-Git % git log
commit 37a35d36eaf8b56c9e7b719c3c7576f3251cee36 (HEAD -> main)
Author: orion-orion <orion-orion@foxmail.com>
Date: Mon May 23 14:15:21 2022 +0800
modify .gitignore
commit ab7bf6e2c400c8d775cc3bc56928c7748c63c8f8
Author: orion-orion <orion-orion@foxmail.com>
Date: Mon May 23 10:08:08 2022 +0800
add .gitignore
commit 146c68e12fd2aebed8b38dd5cf95621f800fe4aa (origin/main, origin/HEAD)
Author: 獵戶座 <46917784+orion-orion@users.noreply.github.com>
Date: Sun May 22 09:48:22 2022 +0800
Initial commit
默認不用任何參數的話,git log會按提交時間列出所有的更新,最近的更新排在最上面。 正如你所看到的,這個命令會列出每個提交的 SHA-1 校驗和、作者的名字和電子郵件地址(如果電子郵件名為<46917784+orion-orion@users.noreply.github.com>,說明你在GitHub中將郵件名設置為私有的了,需要去修改一下)、提交時間以及提交說明。
3.2 追加commit操作/修改commit信息
現在我們又對.gitignore進行了修改。但是我們不想又commit一次,而想將其合并在最后一次的modify .gitignore里,使commit記錄更為精簡。我們可以用以下命令:
(base) orion-orion@MacBook-Pro Learn-Git % git add .gitignore
(base) orion-orion@MacBook-Pro Learn-Git % git commit --amend
并在commit信息的編輯界面寫入modify .gitignore(如果要修改commit信息,此處改成其它的即可):
modify .gitignore
# Please enter the commit message for your changes. Lines starting
# with '#' will be ignored, and an empty message aborts the commit.
#
# Date: Mon May 23 14:15:21 2022 +0800
#
# On branch main
# Your branch is ahead of 'origin/main' by 2 commits.
# (use "git push" to publish your local commits)
#
# Changes to be committed:
# modified: .gitignore
# new file: data/.gitkeep
# new file: model/.gitkeep
#
# Changes not staged for commit:
# modified: README.md
#
:wq!
可以看到總的commit記錄沒變,所顯示的最后一次commit記錄的時間也沒變,但新的修改已經追加進去了(SHA-1 校驗和發生了變化):
(base) orion-orion@MacBook-Pro Learn-Git % git log
commit a0dfeff409494165bdff60c27b24fad2bc0ed0ad (HEAD -> main)
Author: orion-orion <orion-orion@foxmail.com>
Date: Mon May 23 14:15:21 2022 +0800
modify .gitignore
commit ab7bf6e2c400c8d775cc3bc56928c7748c63c8f8
Author: orion-orion <orion-orion@foxmail.com>
Date: Mon May 23 10:08:08 2022 +0800
add .gitignore
commit 146c68e12fd2aebed8b38dd5cf95621f800fe4aa (origin/main, origin/HEAD)
Author: 獵戶座 <46917784+orion-orion@users.noreply.github.com>
Date: Sun May 22 09:48:22 2022 +0800
Initial commit
我們在暫存區沒有任何更新的情況下,也可以使用git commit --amend命令來單純修改commit操作的附加信息。
但是上面的操作只能修改最近一次的commit信息,如果我們要修改幾步之前的commit信息呢?這時就要用到git rebase操作了。
比如如果我們用git log查看到以下修改記錄:
(base) orion-orion@MacBook-Pro Learn-Git % git log
commit 34381d5208c81b2a9846402225cd9a559163c2ef (HEAD -> master
)
Author: orion-orion <orion-orion@foxmail.com>
Date: Mon Aug 1 14:39:43 2022 +0800
add file4
commit 12eb0b1bdbdc41a8d7b1b63ed777135de2396e25
Author: orion-orion <orion-orion@foxmail.com>
Date: Mon Aug 1 14:39:27 2022 +0800
add file3
commit 123ac795a8a283c89737eeb83d2a62210c55cc0c
Author: orion-orion <orion-orion@foxmail.com>
Date: Mon Aug 1 14:39:11 2022 +0800
add file*
commit b04ef5bbf5bf70296790c7e9fbe71b27afd04a3f
Author: orion-orion <orion-orion@foxmail.com>
Date: Mon Aug 1 14:38:46 2022 +0800
add file1
現在我們覺得導數第3個commit記錄不太和諧,想把它修改為add file2。那么我們需要使用git rebase -i HEAD~3。注意:這里HEAD~0為當前工作的分支,HEAD/HEAD~1為上次提交發生之前的工作分支,HEAD~3為上上上次提交發生之前的工作分支,此處git rebase -i HEAD~3即為將HEAD指針指向上上上次提交發生之前的工作分支。
PS: 在Git中分支就是指向提交對象的可變指針。
然后顯示
pick 123ac79 add file*
pick 12eb0b1 add file3
pick 34381d5 add file4
需要在編輯模式下將第一行的pick修改為edit:
edit 123ac79 add file*
pick 12eb0b1 add file3
pick 34381d5 add file4
然后在底行模式輸入:wq保存退出。最后再和上面一樣輸入git commit --amend(如果還需要追加文件,則在這之前還需要使用git add命令將文件添加到暫存區),顯示:
add file*
# Please enter the commit message for your changes. Lines starting
# with '#' will be ignored, and an empty message aborts the commit.
...
需要再編輯模式下將add file*修改為add file2:
add file2
# Please enter the commit message for your changes. Lines starting
# with '#' will be ignored, and an empty message aborts the commit.
...
此時輸入git log,可以看到已經修改完畢,不過HEAD指針是指向add file2對應的commit對象的:
(base) orion-orion@MacBook-Pro Learn-Git % git log
commit 19f39c0883a0b5b9e7ebcef4e9efd82c72e8bb44 (HEAD)
Author: orion-orion <orion-orion@foxmail.com>
Date: Mon Aug 1 14:39:11 2022 +0800
add file2
commit b04ef5bbf5bf70296790c7e9fbe71b27afd04a3f
Author: orion-orion <orion-orion@foxmail.com>
Date: Mon Aug 1 14:38:46 2022 +0800
add file1
為了回到我們原來的master分支,我們需要運行git rebase --continue命令。運行完畢后。再使用git log查看commit記錄,可以看到HEAD指針已經指向了原來的add file4對應的commit對象,也就是master分支指針指向的對象,且commit記錄已經正確修改:
(base) orion-orion@MacBook-Pro Learn-Git % git log
commit f4fd696d9b2ff0649adf89e93f7fd767d7c37922 (HEAD -> master)
Author: orion-orion <orion-orion@foxmail.com>
Date: Mon Aug 1 14:39:43 2022 +0800
add file4
commit 27de88d3e66b36f67b3d0eec45759e365951819c
Author: orion-orion <orion-orion@foxmail.com>
Date: Mon Aug 1 14:39:27 2022 +0800
add file3
commit 19f39c0883a0b5b9e7ebcef4e9efd82c72e8bb44
Author: orion-orion <orion-orion@foxmail.com>
Date: Mon Aug 1 14:39:11 2022 +0800
add file2
commit b04ef5bbf5bf70296790c7e9fbe71b27afd04a3f
Author: orion-orion <orion-orion@foxmail.com>
Date: Mon Aug 1 14:38:46 2022 +0800
add file1
此處的HEAD分支指向了最新的commit對象,也就意味著和master分支重合了,它們的關系如下圖所示:
PS:注意,Git的默認分支名字就是
master, 在多次提交操作之后,你其實已經有一個指向最后那個提交對象的 master 分支。 它會在每次的提交操作中自動向前移動,所以默認的master分支會一直指向最新的提交對象。但同樣需要注意的是,Git 的
master分支并不是一個特殊分支。 它就跟其它分支完全沒有區別。 之所以幾乎每一個倉庫都有master分支,是因為git init命令默認創建它,并且大多數人都懶得去改動它。
最后,我們再說一下HEAD~{n}(Tilde)和HEAD^{n}(Caret)的區別。在大多數情況下,~ 表示在提交樹上直接進行線性回溯(默認每個節點都選擇其第一個parent),而^則用于在提交樹上選擇當前節點的不同parent。注意,在提交樹沒有分叉時,二者等價。
我們以下面這個提交樹為例子來講解。這里有上到下對應由遠及近的時間順序,其中D、F、B、A都為merge commit。節點B和C是A節點的parents,parents按照從左到右的提交順序。
G H I J
\ / \ /
D E F
\ | / \
\ | / |
\|/ |
B C
\ /
\ /
A
則我們有下面的等價關系:
A = A~0 = A^0
B = A^ = A^1 = A~1
C = A^2
D = A^^ = A^1^1 = A~2
E = B^2 = A^^2
F = B^3 = A^^3
G = A^^^ = A^1^1^1 = A~3
H = D^2 = B^^2 = A^^^2 = A~2^2
I = F^ = B^3^ = A^^3^
J = F^2 = B^3^2 = A^^3^2
3.3 撤銷git commit操作
現在我們想撤銷git commit的操作。我們回到在2.2節中提到的git reset命令。不過現在我們需要使用git reset --soft方法,比如如果我們用git log`查看到以下修改記錄:
(base) orion-orion@MacBook-Pro Learn-Git % git log
commit 3f1ea3da4bd477b511c5a6eb0ddc8620b0d3b34f (HEAD -> master)
Author: orion-orion <orion-orion@foxmail.com>
Date: Mon Aug 1 15:46:23 2022 +0800
add file4
commit 0755827bbb67c463cb7ac139f1f86c93006a26e0
Author: orion-orion <orion-orion@foxmail.com>
Date: Mon Aug 1 15:45:58 2022 +0800
add file3
commit 19f39c0883a0b5b9e7ebcef4e9efd82c72e8bb44
Author: orion-orion <orion-orion@foxmail.com>
Date: Mon Aug 1 14:39:11 2022 +0800
add file2
commit b04ef5bbf5bf70296790c7e9fbe71b27afd04a3f
Author: orion-orion <orion-orion@foxmail.com>
Date: Mon Aug 1 14:38:46 2022 +0800
add file1
我們想撤銷掉上一次的add file4對應的提交,需要運行git reset --soft HEAD~1命令:
commit 0755827bbb67c463cb7ac139f1f86c93006a26e0 (HEAD -> master)
Author: orion-orion <orion-orion@foxmail.com>
Date: Mon Aug 1 15:45:58 2022 +0800
add file3
commit 19f39c0883a0b5b9e7ebcef4e9efd82c72e8bb44
Author: orion-orion <orion-orion@foxmail.com>
Date: Mon Aug 1 14:39:11 2022 +0800
add file2
commit b04ef5bbf5bf70296790c7e9fbe71b27afd04a3f
Author: orion-orion <orion-orion@foxmail.com>
Date: Mon Aug 1 14:38:46 2022 +0800
add file1
命令中的HEAD~1意思為將撤銷掉上次提交的記錄,HEAD~2則為撤銷上上次提交之后的所有記錄,其余以此類推。
git reset命令可連續使用(對于--mixed、--soft和我們下面將要介紹的--hard選項都如此),比如我們再使用一次命令git reset --soft HEAD~1就會再繼續撤銷掉上上次提交的記錄:
commit 19f39c0883a0b5b9e7ebcef4e9efd82c72e8bb44 (HEAD -> master)
Author: orion-orion <orion-orion@foxmail.com>
Date: Mon Aug 1 14:39:11 2022 +0800
add file2
commit b04ef5bbf5bf70296790c7e9fbe71b27afd04a3f
Author: orion-orion <orion-orion@foxmail.com>
Date: Mon Aug 1 14:38:46 2022 +0800
add file1
注意,reset命令還可以選擇--hard選項。--hard選項與soft選項的區別在于,使用--hard選項不僅會撤銷掉最后一次的commit,同時也會修改working tree,也就是當前的工作目錄。事實上,--hard 標記是reset命令唯一的危險用法,它也是 Git 會真正地銷毀數據的僅有的幾個操作之一。 其他任何形式的reset調用都可以輕松撤消,但是--hard選項不能,因為它強制覆蓋了工作目錄中的文件。因此,使用--hard選項時要多加小心。
參考
- [1] 《Pro Git 中文版》在線閱讀
- [2] Stack Overflow: How can I Remove .DS_Store files from a Git repository?
- [3] Stack Overflow: How can I add a blank directory to a Git repository?
- [4] Local Coder: Difference between .gitignore rules with and without trailing slash like /dir and /dir/
- [5] Stack Overflow: Difference between "git add -A" and "git add ."
- [6] 知乎:為什么要先 git add 才能 git commit ?
- [7] 知乎:Git commits歷史是如何做到如此清爽的?
- [8] Stack Overflow: "git rm --cached x" vs "git reset head --? x"?
- [9] Stack Overflow: "What's the difference between HEAD^ and HEAD~ in Git?"

.gitignore針對每個語言都有對應的模板,在GitHub創建項目時就可以選擇(你可以在GitHub提供的.gitignore模板大全中找到它)。但是這些往往是不夠的的。如我們在Mac系統下用VSCode開發,那么常常還需要添加其它項目。如.vscode/表示忽略.vscode這個包含項目配置文件的隱藏目錄(注意是包括目錄一起忽略,.DS_Store表示忽略掉Mac操作系統下存儲目錄自定義屬性的隱藏文件。此外機器學習相關的項目中,數據和模型通常異常巨大,我們并不想將它們放到項目文件夾下。
浙公網安備 33010602011771號