Git:用git clean排除文件

san*_*lto 34 git version-control git-clean

我正在开发一个大型python项目,如果.pyc和*〜文件,我真的很生病.我想删除它们.我已经看到-Xgit clean 的标志会删除未跟踪的文件.你可以想象,我不是跟踪.pyc也不是*~文件.那就是诀窍.问题是我有一个local_settings.py文件,我想在git clean之后保留.

所以,这就是我所拥有的.

的.gitignore:

*.pyc
*~
local_settings.py
Run Code Online (Sandbox Code Playgroud)

当我执行此命令时:

git clean -X -n -e local_settings.py
Run Code Online (Sandbox Code Playgroud)

我得到这个结果列表:

将删除local_settings.py
将删除requirements.txt~
将删除(其他一堆)〜文件
将删除(其他一堆)pyc文件

我不想删除local_settings.py文件.我已经尝试了很多方法来做到这一点,但我无法弄清楚如何完成它.

git clean -X -n -e local_settings.py
git clean -X -n -e "local_settings.py"
git clean -X -n --exclude=local_settings.py
git clean -X -n --exclude="local_settings.py"
Run Code Online (Sandbox Code Playgroud)

似乎没有任何工作.

编辑:

对于后代,正确的方法是(谢谢@Rifat):

git clean -x -n -e local_settings.py # Shows what would remove (-n flag)
git clean -x -f -e local_settings.py # Removes it (note the -f flag)
Run Code Online (Sandbox Code Playgroud)

Rif*_*fat 27

请你试试小x而不是资本.喜欢 -git clean -x

git clean -x -n -e local_settings.py # Shows what would remove (-n flag)
git clean -x -f -e local_settings.py # Removes it (note the -f flag)
Run Code Online (Sandbox Code Playgroud)

git文档:

   -x
       Don't use the standard ignore rules read from .gitignore (per
       directory) and $GIT_DIR/info/exclude, but do still use the ignore
       rules given with -e options. This allows removing all untracked
       files, including build products. This can be used (possibly in
       conjunction with git reset) to create a pristine working directory
       to test a clean build.

   -X
       Remove only files ignored by git. This may be useful to rebuild
       everything from scratch, but keep manually created files.
Run Code Online (Sandbox Code Playgroud)

  • 使用 `-X` 你必须用 `!` 作为路径前缀(如@forivall 所建议) (3认同)

for*_*all 16

git clean -X -n --exclude="!local_settings.py"
Run Code Online (Sandbox Code Playgroud)

作品.当我用Google搜索并获得此页面时,我发现了这一点.

  • 好的!谢谢。:) 我不得不在 shell 中去掉“!”,但它有效。 (3认同)
  • 啊哈!现在我懂了。`-X` 还反转了 `-e` 选项的行为!哪一种有道理。这就是为什么我们需要“!”(我删除了之前的评论以避免混淆) (3认同)
  • 就我而言,我必须转义感叹号,所以这对我来说可以删除除名为“.idea”的文件夹之外的所有内容: `git clean -X -n -e \!.idea` (2认同)

Jon*_*ham 5

我将属于此类别的本地文件放在 .git/info/exclude 中(例如我的 IDE 项目文件)。你可以像这样进行清理:

git ls-files --others --exclude-from=.git/info/exclude -z | \
    xargs -0 --no-run-if-empty rm --verbose
Run Code Online (Sandbox Code Playgroud)

在哪里:

  • --others:显示未跟踪的文件
  • --exclude-from:提供标准 git 忽略样式文件以从列表中排除
  • -z / -0:使用\0而不是\n来分割名称
  • --no-run-if-empty:如果列表为空,则不运行 rm

您可以创建一个别名,例如:

git config --global alias.myclean '!git ls-files --others --exclude-from=.git/info/exclude -z | xargs -0 --no-run-if-empty rm --verbose --interactive'
Run Code Online (Sandbox Code Playgroud)

--interactive 意味着您必须执行 git myclean -f 来强制删除。

参考: http: //git-scm.com/docs/git-ls-files(加上默认.git/info/exclude的第一行)