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

后端 未结 30 2483
离开以前
离开以前 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:18

    Adding one more option to the fray.

    Assuming you would like to add a directory to git that, for all purposes related to git, should remain empty and never have it's contents tracked, a .gitignore as suggested numerous times here, will do the trick.

    The format, as mentioned, is:

    *
    !.gitignore
    

    Now, if you want a way to do this at the command line, in one fell swoop, while inside the directory you want to add, you can execute:

    $ echo "*" > .gitignore && echo '!.gitignore' >> .gitignore && git add .gitignore
    

    Myself, I have a shell script that I use to do this. Name the script whatever you whish, and either add it somewhere in your include path, or reference it directly:

    #!/bin/bash
    
    dir=''
    
    if [ "$1" != "" ]; then
        dir="$1/"
    fi
    
    echo "*" > $dir.gitignore && \
    echo '!.gitignore' >> $dir.gitignore && \
    git add $dir.gitignore
    

    With this, you can either execute it from within the directory you wish to add, or reference the directory as it's first and only parameter:

    $ ignore_dir ./some/directory
    

    Another option (in response to a comment by @GreenAsJade), if you want to track an empty folder that MAY contain tracked files in the future, but will be empty for now, you can ommit the * from the .gitignore file, and check that in. Basically, all the file is saying is "do not ignore me", but otherwise, the directory is empty and tracked.

    Your .gitignore file would look like:

    !.gitignore
    

    That's it, check that in, and you have an empty, yet tracked, directory that you can track files in at some later time.

    The reason I suggest keeping that one line in the file is that it gives the .gitignore purpose. Otherwise, some one down the line may think to remove it. It may help if you place a comment above the line.

提交回复
热议问题