How to Get Just One File from Another Branch
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:
- Identify the file and the branch:
- Determine the file you want to retrieve and the branch where it is located.
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
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 getexample.txt
from thefeature-branch
, you would run:git checkout <branch> -- <file>
git checkout feature-branch -- path/to/example.txt
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:
Ensure you are on the
main
branch:git checkout main
Checkout the
readme.txt
file from thedevelop
branch:git checkout develop -- docs/readme.txt
(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.
Make your mark
Join the writer's program
Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.
Write for usBuild on top of Better Stack
Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.
community@betterstack.comor submit a pull request and help us build better products for everyone.
See the full list of amazing projects on github