git clean
使用 Git 版本管理的时候,在常见的 IDE 工具 (如:PyCharm) 上看到未跟踪的文件都会与其它文件是有区别的,如文件名为红色。因此,当想要移除未跟踪的文件的时候会很简单。但是,当项目大并且未跟踪的文件很多分布在各个文件夹里面的时候,或者当没有这些方便的 IDE 工具给你的时候,你想要移除这些未跟踪文件还是很麻烦的。那么有没有方便的方法呢?
1 | git-clean - Remove untracked files from the working tree |
用法1
git clean [-d] [-f] [-i] [-n] [-q] [-e <pattern>] [-x | -X] [--] <path>...
git clean 默认从当前目录开始递归移除不在版本管理下的文件,如未跟踪的文件。也可以指定开始的目录 <path>。
git clean 常用参数:
-n, --dry-run
Don’t actually remove anything, just show what would be done.-n参数不会真正移除任何东西,仅仅展示当前命令将要做的工作给你看。很有用的一个参数,可以让我们清晰的知道将要移除那些东西。1
2
3
4
5
6
7
8
9
10
11
12
13
14# creating a new file test1.py on current clean working tree
$ touch test1.py
$ git status -s
?? test1.py
$ git clean -n
Would remove test1.py
# creating a new directory d1 and a new file test2.py in it
$ mkdir d1
$ touch d1/test2.py
$ git status -s
?? d1/
?? test1.py
$ git clean -n
Would remove test1.py一个很奇怪的现象:当新建一个空目录 (d1),并在该目录下新建一个文件 (test2.py) 的时候,会发现该文件 (d1/test2.py) 不会被
git clean移除!怎么回事?-d
Remove untracked directories in addition to untracked files.-d参数不但会移除未跟踪的文件,还会移除未跟踪的目录。但是,如果未跟踪的目录被其它分支管理的话,将不会被移除。的确要移除只能够用-f强制性移除。接着上面的操作来看看:1
2
3$ git clean -nd
Would remove d1/
Would remove test1.py可以看到
d1文件夹以及里面的内容都将会被移除。注意当文件夹里面有文件被跟踪的时候,这个目录实际上已经被跟踪了。1
2
3
4
5
6
7
8
9$ touch d1/test3.py
$ git add d1/test3.py
$ git status -s
A d1/test3.py
?? d1/test2.py
?? test1.py
$ git clean -nd
Would remove d1/test2.py
Would remove test1.py-f, --force-f参数会强制性执行移除操作。-i, --interactive
Show what would be done and clean files interactively.-i会启动一个交互式的操作界面,你可以进一步确定那些东西要移除。-x-x参数可以删除包括已经被.gitignore文件忽略的文件。接着上面的操作:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19$ touch test4.py d1/test5.py
$ git status -s
A d1/test3.py
M .gitignore
?? d1/test2.py
?? d1/test5.py
?? test1.py
?? test4.py
$ cat <<EOF >> .gitignore
test4.py
d1/test5.py
$ git clean -n # the .gitignore files won't be removed
Would remove d1/test2.py
Would remove test1.py
$ git clean -nx # the .gitignore files will be removed too
Would remove d1/test2.py
Would remove d1/test5.py
Would remove test1.py
Would remove test4.py可以看到
git clean是不会移除.gitignore忽略的文件的,添加-x参数可以移除.gitignore忽略的文件。-X
Remove only files ignored by Git.
仅仅移除被.gitignore文件忽略的文件。接着上面操作:1
2
3
4$ git clean -nX
...
Would remove d1/test5.py
Would remove test4.py