Replicating the Checkout Error
To understand how to fix the error, we first need to replicate it. This will help clarify why Git reports a conflict. Our setup script has already created a Git repository with two branches: main and feature-branch. The feature-branch contains a file that we will now create locally in the main branch.
First, navigate to the project directory. All commands in this lab will be run from this directory.
cd ~/project/git-checkout-demo
Let's check the current status of our repository to ensure everything is clean.
git status
The output should be:
On branch main
nothing to commit, working tree clean
This confirms we are on the main branch with no pending changes. Now, let's list the available branches.
git branch
You will see the two branches, with * indicating the current branch:
feature-branch
* main
Now, let's create the conflict. We will create a new file named feature.md in our current working directory. This file is currently "untracked" by Git on the main branch, but a file with the same name already exists and is tracked on feature-branch.
echo "## My local changes to feature documentation" > feature.md
Check the status again to see the new untracked file.
git status
The output now shows feature.md as an untracked file:
On branch main
Untracked files:
(use "git add <file>..." to include in what will be committed)
feature.md
nothing added to commit but untracked files present (use "git add" to track)
Finally, let's attempt to switch to the feature-branch.
git checkout feature-branch
This command will fail and produce the error we are studying:
error: The following untracked working tree files would be overwritten by checkout:
feature.md
Please move or remove them before you switch branches.
Aborting
Git has aborted the checkout to protect your local, untracked feature.md file from being overwritten by the version from feature-branch. In the next steps, we will explore different ways to resolve this.