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 work­ing direc­tory in A and are uncom­mited. There­fore when you try to switch branches, you end up with git com­plain­ing that you have untracked files that will be over­writ­ten by tracked files.

There are 2 ways solve this prob­lem — one a lit­tle less risky than the other

Less risky
This one is a non-risky way since if you sud­denly 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 def­i­nitely lose all your work­ing direc­tory 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 com­mand reverts the changes to any tracked files. The sec­ond com­mand cleans the project folder of any untracked files and direc­to­ries. 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 *