Matt W
Matt W

Reputation: 12423

Why are folders left in my local git working directory after commit and checkout

I have created a folder containing files in my local working git structure. I created a new branch with git checkout -b and used git add . and git commit -m "..." to add those files to my local branch. But, when I do git checkout master the folder I created and committed is still there. Why? I thought git commit would put the folder and its contents into my local branch, switching it out when I checkout master.

Upvotes: 11

Views: 4376

Answers (1)

Zachary Espiritu
Zachary Espiritu

Reputation: 987

If you add previously untracked files to a new branch, and then you checkout another branch that doesn't currently track those files, it won't remove them from your working copy.

Here's an example—let's say I'm currently on a clean branch named old_branch, and I checkout a new branch named new_branch:

git checkout -b new_branch

Then, I create a new file named test.txt in this branch and add it to the repo:

touch test.txt  # creates a new file named test.txt
git add test.txt
git commit -m "Added test.txt"

The test.txt file is currently tracked by the new_branch branch. However, when I switch branches back to old_branch:

git checkout old_branch

Since test.txt is not tracked by old_branch, it leaves it in the working directory and doesn't overwrite it. This is expected behavior. If you do git status at this point, you'll notice that the test.txt file is currently untracked.


For completion's sake, if you need to clean your working copy of all untracked files, you can first do:

git clean -n

This will list all untracked files that will be removed. If you're satisfied with the list, you can them remove those files with:

git clean -f -d

This is a destructive command, especially since it deletes files that are not tracked by the current branch. (It won't delete them from branches that do track those files though.)

Upvotes: 10

Related Questions