How to Get Just One File from Another Branch

Better Stack Team
Updated on July 25, 2024

To get a single file from another branch in Git, you can use the git checkout command. Here’s how to do it step by step:

  1. Identify the file and the branch:
    • Determine the file you want to retrieve and the branch where it is located.
  2. Switch to your working branch:

    • Make sure you are on the branch where you want to bring the file. For example, if you are on the main branch, you can confirm this by running:

       
      git checkout main
      
  3. Checkout the file from the other branch:

    • Use the git checkout command to get the specific file from the other branch. The syntax is: Replace <branch> with the name of the branch containing the file and <file> with the path to the file. For example, to get example.txt from the feature-branch, you would run:

       
      git checkout <branch> -- <file>
      
       
      git checkout feature-branch -- path/to/example.txt
      
  4. Add and commit the file (optional):

    • After checking out the file, you might want to add and commit it to your current branch:

       
      git add path/to/example.txt
      git commit -m "Add example.txt from feature-branch"
      

Example

Let's say you are on the main branch and you want to retrieve docs/readme.txt from the develop branch. You would do the following:

  1. Ensure you are on the main branch:

     
    git checkout main
    
  2. Checkout the readme.txt file from the develop branch:

     
    git checkout develop -- docs/readme.txt
    
  3. (Optional) Add and commit the file:

     
    git add docs/readme.txt
    git commit -m "Add readme.txt from develop branch"
    

By following these steps, you can successfully get a single file from another branch without affecting the rest of your working directory.

Got an article suggestion? Let us know
Explore more
Git
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.