Git Submodules: Error When Switching Branches
If you've received 'error: The following untracked working tree files would be overwritten by checkout', you are likely using git submodules. Here is how to get around that error.
If you’ve received the error “The following untracked working tree files would be overwritten by checkout” you are likely using git submodules. Git Submodules are a tool that allows you to pull in a separate working tree, often another repository, into an existing repository. Submodules are handy for code isolation and code management within an organization. When working in a repository that leverages submodules you could potentially see errors when you try to checkout or switch to a different branch.
Steps to reproduce:
git checkout my-feature-brancherror: The following untracked working tree files would be overwritten by checkoutgit statusOn branch main nothing to commit, working directory clean
Solution
In this case we have to force a checkout, ignoring the untracked files, using the -f flag.
git checkout my-feature-branch -f
This will at least allow us to switch branches. To more permanently fix the issue we need to remove and re-add the submodules.
rm -rf /path/to/submodulegit checkout maingit merge my-feature-branchgit submodule foreach git fetch --tagsgit submodule update --init --recursive
By executing a few more commands we’re effectively updating the main branch with the code from my-feature-branch.