How can I add an empty directory to a Git repository?

后端 未结 30 2626
离开以前
离开以前 2020-11-21 04:52

How can I add an empty directory (that contains no files) to a Git repository?

30条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-21 05:27

    Sometimes you have to deal with bad written libraries or software, which need a "real" empty and existing directory. Putting a simple .gitignore or .keep might break them and cause a bug. The following might help in these cases, but no guarantee...

    First create the needed directory:

    mkdir empty
    

    Then you add a broken symbolic link to this directory (but on any other case than the described use case above, please use a README with an explanation):

    ln -s .this.directory empty/.keep
    

    To ignore files in this directory, you can add it in your root .gitignore:

    echo "/empty" >> .gitignore
    

    To add the ignored file, use a parameter to force it:

    git add -f empty/.keep
    

    After the commit you have a broken symbolic link in your index and git creates the directory. The broken link has some advantages, since it is no regular file and points to no regular file. So it even fits to the part of the question "(that contains no files)", not by the intention but by the meaning, I guess:

    find empty -type f
    

    This commands shows an empty result, since no files are present in this directory. So most applications, which get all files in a directory usually do not see this link, at least if they do a "file exists" or a "is readable". Even some scripts will not find any files there:

    $ php -r "var_export(glob('empty/.*'));"
    array (
      0 => 'empty/.',
      1 => 'empty/..',
    )
    

    But I strongly recommend to use this solution only in special circumstances, a good written README in an empty directory is usually a better solution. (And I do not know if this works with a windows filesystem...)

提交回复
热议问题