Remove all untracked files and directories before switching branches

Lets say that you want to switch from branch A to B. B has already has some files that have the same name as the ones that are only in the working directory in A and are uncommited. Therefore when you try to switch branches, you end up with git complaining that you have untracked files that will be overwritten by tracked files.

There are 2 ways solve this problem – one a little less risky than the other

Less risky
This one is a non-risky way since if you suddenly decide that you want to retain those changes, you can still get them back from the stash if you didnt drop them.

git stash
git stash drop
git checkout B

More Risky
This one has a higher risk since you will most definitely lose all your working directory changes in a non-recoverable way the moment you run the first 2 commands.

Go to your project root, then

git rest --hard HEAD
git clean -f -d
git checkout B

The first command reverts the changes to any tracked files. The second command cleans the project folder of any untracked files and directories. Now you dont have any way to recover these changes.


Ryan Sukale

Ryan is just a regular guy next door trying to manage his life and finances.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *