Git Error: untracked files would be overwritten by checkout
While using git to keep track of your changes in your project, many things can happen that cause an error. When you move from one branch to another, you might get this error:
error: the following untracked working tree files would be overwritten by checkout [ List of Files Here ] Please, commit your changes or stash them before you can switch branches.
This error occurs when you have files that are on the current branch that have changes on the branch you are working on as well. The fix is fairly simple: do exactly what the last statement says in the error.
To commit the changes, you would input the following:
git commit -m "Insert meaningful git commit message here"
This should clean out your working tree. And then use
git checkout <name-of-branch>
to change branches.
Use git stash to store your changes until you are ready to commit. Git stash will conserve your changes, but not associate them with any commit or branch until you are ready.
To use stash, do the following in your local repository:
git stash push git checkout <branch-you-need-to-switch-to> --- do whatever you have to do on <branch-you-need-to-switch-to> --- git checkout <previous-branch> git stash pop
If you are familiar with how a stack works, this is straightforward. As a reminder, a stack is a last-in-first-out (LIFO) data structure. The latest stash is added to the end of the list. Pop it off when you are ready to use it.
The default behavior is to pop off the last element in the stash list and completely remove it. If you don’t want to get rid of the stash, but simply just use it, you can do that with
git stash apply
In this article, we looked at two ways to correct an working tree file error that would be overwritten on checkout. Most times, we can do exactly what the git error says to correct it. In this instance, we can either commit the changes or stash the changes to clear the working tree so we can change branches. Which one you decide to do to clear out your error is dependent on what your team’s git workflow is. Always ask for help if you’re unsure of which to do. Happy hacking!