How to handle 'error: untracked working tree files would be overwritten by checkout' in Git

GitBeginner
Practice Now

Introduction

Git is a powerful version control system essential for modern software development. While using Git, you may encounter the error message: "error: untracked working tree files would be overwritten by checkout". This error occurs when you try to switch branches, but Git detects that this action would overwrite files in your current working directory that are not yet tracked by Git. This safety feature prevents accidental data loss.

In this lab, you will learn the cause of this common error, how to identify the conflicting files, and several methods to resolve it. By the end of this tutorial, you will be able to manage your Git workflow more effectively and handle this error with confidence.

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.

Resolving the Conflict with git stash

One of the safest and most common ways to resolve this error is by using git stash. This command temporarily saves your local modifications (both staged and unstaged) and reverts the working directory to match the last commit. This allows you to switch branches freely.

We are currently on the main branch with the untracked feature.md file causing the conflict.

To stash untracked files, you need to use the --include-untracked (or -u) option.

git stash push --include-untracked

You will see a confirmation message:

Saved working directory and index state WIP on main: <commit_hash> Initial commit with README

Now, check the status of your repository again.

git status

The working tree is clean, and the untracked file is gone:

On branch main
nothing to commit, working tree clean

With the working directory clean, you can now switch to the feature-branch without any errors.

git checkout feature-branch

The command will succeed:

Switched to branch 'feature-branch'

You are now on the feature-branch. If you inspect feature.md, you will see the version that belongs to this branch.

cat feature.md
## Official Feature Documentation

Your local changes are safely stored in the stash. To get them back, you can switch back to the main branch and apply the stash.

git checkout main
git stash pop

The git stash pop command reapplies the stashed changes and removes them from the stash list. Your feature.md file is now back in your working directory.

For the next step, let's ensure we are back in the conflict state. If you followed the git stash pop command, you are already there.

Resolving the Conflict with git clean

Another way to resolve the conflict is to delete the untracked files. This method is suitable only when you are certain that you do not need the untracked files. The git clean command is used for this purpose.

Warning: This command permanently deletes files, so use it with caution.

First, let's ensure we are in the conflict state on the main branch with the untracked feature.md file.

cd ~/project/git-checkout-demo
git checkout main
## If feature.md doesn't exist, recreate it
if [ ! -f "feature.md" ]; then echo "## My local changes" > feature.md; fi
git status

Before deleting anything, it is a best practice to perform a "dry run" using the -n flag. This will show you which files would be deleted without actually deleting them.

git clean -n

The output will list the files to be removed:

Would remove feature.md

Once you have confirmed that you want to delete these files, you can run the command again with the -f (force) flag.

git clean -f

Git will confirm the removal:

Removing feature.md

Now that the untracked file is gone, your working directory is clean, and you can switch branches without issue.

git checkout feature-branch

The checkout will be successful.

Switched to branch 'feature-branch'

This method is fast but destructive. The git stash method from the previous step is generally safer because it preserves your work.

Resolving by Tracking the File and Best Practices

Sometimes, the untracked file is not disposable; it's work you want to keep. In this case, the correct approach is to add the file to Git's tracking system by committing it. This section also covers best practices to prevent this error from happening in the first place.

First, let's return to the main branch and recreate our conflicting file.

cd ~/project/git-checkout-demo
git checkout main
echo "## My local changes to feature documentation" > feature.md

Method: Track the File

If the untracked file is important, you should commit it to the current branch.

  1. Add the file to the staging area.

    git add feature.md
  2. Commit the staged file.

    git commit -m "Add local version of feature.md"

Now that your changes are safely committed to the main branch, Git can handle the switch. When you check out feature-branch, Git will simply replace the workspace file with the version from that branch.

git checkout feature-branch

The checkout is successful. Your committed changes are safe in the main branch's history.

Best Practice: Use .gitignore

To prevent certain files (like logs, build artifacts, or environment files) from ever being tracked, you should use a .gitignore file. Git will ignore any files or directories matching the patterns in .gitignore, preventing them from becoming conflicting untracked files.

Let's create a .gitignore file to ignore all .log files.

## Switch back to main to add the .gitignore file
git checkout main

## Create the .gitignore file
echo "*.log" > .gitignore

Now, create a log file.

touch app.log

Check the status.

git status

Notice that app.log does not appear as an untracked file. However, the .gitignore file itself is untracked.

On branch main
Untracked files:
  (use "git add <file>..." to include in what will be committed)
	.gitignore

nothing added to commit but untracked files present (use "git add" to track)

You should always commit your .gitignore file so the rules are shared across the project.

git add .gitignore
git commit -m "Add .gitignore to ignore log files"

By committing often and using .gitignore effectively, you can significantly reduce the chances of encountering this checkout error.

Summary

In this lab, you have learned how to diagnose and resolve the "error: untracked working tree files would be overwritten by checkout" in Git.

You accomplished the following:

  1. Replicated the Error: You successfully created a scenario that triggers the error, providing a clear understanding of its cause.
  2. Resolved with git stash: You learned how to use git stash to temporarily save untracked files, allowing you to switch branches safely without losing work.
  3. Resolved with git clean: You learned how to use git clean to remove untracked files when they are no longer needed, after first performing a dry run to avoid mistakes.
  4. Resolved by Tracking Files: You learned to resolve the issue by committing the untracked file, which is the correct approach for work you intend to keep.
  5. Learned Best Practices: You learned how to use a .gitignore file to prevent temporary or build-related files from causing conflicts.

By mastering these techniques, you can maintain a cleaner, more efficient Git workflow and confidently handle one of the most common issues faced by developers.