Elena' s AI Blog

Git Checkout for overwriting directories from different branches

22 Sep 2024 (updated: 05 Oct 2026) / 7 minutes to read

Elena Daehnhardt

Git checkout to overwrite a directory contents


TL;DR:
  • How to overwrite a directory in one Git branch with contents from another branch using git checkout command, with cautionary notes about file replacement.

Previous: Part 24 β€” Git Remotes

Next: Part 26 β€” GitHub Gists

Git Checkout Directory From Another Branch: How to Overwrite Its Contents

To checkout a directory (or folder) from another branch and overwrite its contents on your current branch, run git checkout <source-branch> -- <path>/ and commit the result. The same command also works to replace a single file with its version from another branch β€” for example, git checkout dev -- scripts/ replaces the scripts/ directory on your current branch with the version from dev, and git checkout dev -- path/to/file.py replaces just that one file.

Recently, I had to overwrite the β€œscripts” directory in my master branch with the files stored in the β€œscripts” directory of the β€œdev” branch. Here, I share the simplest way to overwrite the required directory completely with the respective directory contents from another branch.

Use this git checkout command with caution, since it completely rewrites your files in the destination branch.

What git checkout does, the step-by-step version and the common pathspec error follow below.

What is git checkout?

πŸ”’ Subscribe to keep reading.

Overwrite a Directory from Another Branch: Step-by-Step git checkout Commands

πŸ”’ Subscribe to keep reading.

error: pathspec β€˜dev’ did not match any file(s) known to git

πŸ”’ Subscribe to keep reading.

Conclusion: git checkout Overwrites a Directory Path in One Command

πŸ”’ Subscribe to keep reading.

References

πŸ”’ Subscribe to keep reading.

You've hit a Deep Dive tutorial.

I spend dozens of hours researching, coding, and breaking things to write these guides. This content is free, but reserved for my subscriber community. Drop your email below to unlock this guide (and all past/future deep dives):

Already a subscriber? Use the magic link from your last newsletter, or reset your password.

New subscribers get an inbox mail: Set a password to unlock articles. The form does not log you in β€” use the same email afterwards.

desktop bg dark

About Elena

Elena, a PhD in Computer Science, simplifies AI concepts and helps you use machine learning.

Citation
Elena Daehnhardt. (2024) 'Git Checkout for overwriting directories from different branches', daehnhardt.com, 22 September 2024. Available at: https://daehnhardt.com/blog/2024/09/22/edaehn-git-overwrite-directory-with-contents-from-a-branch/
All Posts