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.
Git Checkout File Checking out a file is similar to using git reset with a file path, except it updates the working directory instead of the stage. Unlike the commit-level version of this command, this does not move the HEAD reference, which means that you won't switch branches.
For now, it's most important to understand that any local (in your working directory) changes that you've made to the file being checked out will be gone. Git will simply copy the most recently-committed version of the file to your working directory, overwriting your copy.
The git checkout command lets you navigate between the branches created by git branch . Checking out a branch updates the files in the working directory to match the version stored in that branch, and it tells Git to record all new commits on that branch.
Git will only track Files and the changes in them. So folders are tracked as part of the file changes in them. In order to create an empty folder and commit it, there have to be some files inside it.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With