【问题标题】:Delete unecessary .keep files删除不必要的 .keep 文件
【发布时间】:2025-12-03 04:55:02
【问题描述】:

我注意到我的 git 存储库有很多 .keep 文件。它们曾经在其父目录为空时很有用,但从那时起,许多目录现在有了真正的子目录,使它们在 git 中保持活力。

有没有删除所有不需要的.keep 文件的好方法?特别是那些:

  1. 大小为 0(无实际内容)
  2. 有准确的名字.keep
  3. 在他们的文件夹中有邻居(即删除他们不会导致他们的父文件夹变空)

我查看了git gcgit clean等的文档,但没有找到这样的功能。

【问题讨论】:

    标签: git version-control file-management file-manipulation


    【解决方案1】:

    Git 没有提及 keep 文件是什么,因此它的名称只是一个约定(.gitkeep.keep 等)。这就是为什么git-clean 不支持类似的东西。我想不出一个非常简单的方法,所以我最终得到了一个像这样的小脚本:

    #!/bin/bash
    
    # read all directories without escaping
    while IFS= read -r DIR; do
        # enter to each directory to simplify parsing
        pushd "$DIR" 1> /dev/null
        # ask git to list all tracked files in the current directory
        #   filtering out the .keep file (the inVerted -v grep switch)
        #   and checking if it is giving more than 1 line
        if [[ $(git ls-files | grep -Pv '^.keep$' | head -1) ]]; then
            # if true, just print out the directory along with its "keep" file
            echo "$DIR/.keep"
        fi
        popd 1> /dev/null
        # the -mindepth would enable the depth-first traversing
        #   (empty files only named .keep and never walk into .git directories -- print out directories only)
    done < <(find -mindepth 1 -not -path '*/\.git/*' -type f -name '.keep' -empty -printf '%h\n')
    

    此脚本将在试运行中打印出所有冗余的.keep 文件。如果生成的like 看起来不错,请使用xargs 进行管道传输:above_script_path | xargs git rm

    【讨论】:

      【解决方案2】:

      正如您从Random 'concerns' folders and '.keep' files 中看到的那样,.keep 文件只是允许文件夹“提交”到存储库的有用文件。

      这是删除所有.keep 文件的命令。然后按照你的意愿提交。

      zrrbite@ZRRBITE MINGW64 /d/dev/git/keeptest (master) 
      $ git ls-files *.keep | xargs git rm                          
      rm '.keep' 
      rm 'test/.keep'
                                                               
      zrrbite@ZRRBITE MINGW64 /d/dev/git/keeptest (master) 
      $ git st                                                     
      ## master                                                    
      D  .keep
      D  test/.keep                                                 
      

      【讨论】:

      • 我并没有试图将它们全部删除,我只想删除那些不会导致其父文件夹删除(粗略地说,因为 git 不跟踪文件夹)的那些
      • 啊。我以为您在空的文件夹中只有.keep 文件,否则。这样,您可以将它们全部删除并且安全。其他.keep 文件是多余的(因为文件夹不为空),可以在需要时添加。我认为这是一种更简洁的方法(在非空文件夹中没有 .keep 文件)。听起来您可能只想删除所有 .keep 文件,因为您不想“保留”空文件夹。
      • 这是一个很大的 repo,有 lots 的贡献者。我不知道他们想要保留某些文件夹以供将来使用的动机,我不想从他们那里拿走它。但是,我可以肯定,其他非空文件中的 .keep 文件肯定是无用的,并且可以轻松删除它们。