How to commit empty folder in git
Find below the steps to add an empty folder into git.
Consider this initial state of a repository repoone. The branch main has four commits. We want to add an empty directory dirtwo.
~/repoone$ git branch
* main
maincopy
maintemp
source
sourcecopy
target
~/repoone$ git log --oneline
908d6ac (HEAD -> main, origin/main, origin/HEAD) Third commit in main
42296d0 Second commit in main
453424e This is first commit
2673111 Initial commit
Try creating an empty directory dirtwo and try “git add”. It would show status as nothing to add.
~/repoone$ mkdir dirtwo
~/repoone$ git add dirtwo
~/repoone$ git status
On branch main
Your branch is up to date with 'origin/main'.
nothing to commit, working tree clean
To add an empty directory, create the directory with file .gitignore inside it. Add the lines as shown below to this file. Now git add allows adding this directory. This directory is still considered empty. You can use commit to creating a new commit into the branch.
~/repoone$ vi dirtwo/.gitignore
~/repoone$ cat dirtwo/.gitignore
# Ignore everything in this directory
*
# Except this file
!.gitignore
~/repoone$ git add dirtwo
~/repoone$ git status
On branch main
Your branch is up to date with 'origin/main'.
Changes to be committed:
(use "git restore --staged <file>..." to unstage)
new file: dirtwo/.gitignore
~/repoone$ git commit -m "Adding empty directory"
[main 4632c0d] Adding empty directory
1 file changed, 4 insertions(+)
create mode 100644 dirtwo/.gitignore
~/repoone$ git log --oneline
4632c0d (HEAD -> main) Adding empty directory
908d6ac (origin/main, origin/HEAD) Third commit in main
42296d0 Second commit in main
453424e This is first commit
2673111 Initial commit