Skip to main content

How to Checkout a Single File from Another Git Branch

Β· 5 min read
Serhii Hrekov
software engineer, creator, artist, programmer, projects founder

Sometimes, you may want to retrieve a specific file from another branch in a Git repository without switching branches completely. This is particularly useful when you want to grab a specific version of a file for debugging, rollback, or review.

In this guide, we’ll walk through how to checkout a single file from another branch using Git. We’ll cover multiple scenarios with examples and best practices.


Why This is Useful​

  • Revert or test a previous version of a file
  • Compare changes between branches
  • Avoid conflicts from switching the full branch
  • Maintain working directory without resets

1. Basic Git Checkout Syntax​

The simplest way to checkout a file from another branch is:

git checkout <branch-name> -- <path-to-file>

βœ… Example​

Let’s say you want to get README.md from the develop branch while on main:

git checkout develop -- README.md

This will replace the current README.md in your working directory with the version from develop.


2. Checkout a File to a Different Name​

You can also checkout the file from another branch and save it under a different name:

git show develop:README.md > README.develop.md

This is useful if you want to compare two versions side-by-side.


3. Checking Out a File in a Subdirectory​

git checkout feature-x -- src/utils/helpers.py

Make sure you provide the relative path from the root of the repo.


4. Listing Files in Another Branch​

If you’re unsure what the exact path of the file is in the other branch:

git ls-tree -r <branch-name> --name-only

Example​

git ls-tree -r develop --name-only | grep requirements.txt

5. Restore File from Another Branch (Git 2.23+)​

Starting with Git 2.23, you can also use git restore:

git restore --source <branch-name> <path-to-file>

Example​

git restore --source develop README.md

This is the modern equivalent of git checkout and more descriptive.


6. Caution: This Overwrites the File​

Be aware that both git checkout and git restore will overwrite your current file.

If you want to keep your local changes, stash them first:

git stash push -m "before file restore"
git checkout <branch> -- <file>
git stash pop

7. Compare File Differences (Optional)​

To view the differences without checking out the file:

git diff <branch-name> -- <file>

This shows the changes between your current working file and the one in another branch.


Summary Table​

TaskCommand Example
Checkout a file from another branchgit checkout develop -- myfile.py
Save file under different namegit show develop:myfile.py > myfile-dev.py
Use restore instead of checkoutgit restore --source develop myfile.py
See diff between branchesgit diff develop -- myfile.py
List files in a branchgit ls-tree -r develop --name-only

Further Reading​