Get One File From Another Branch in Git

How to Get One File From Another Branch in Git

Git version control system allows you to work with multiple branches at the same time. Sometimes you may want to use file from another branch to your present branch. In this article, we will learn how to get one file form another branch in git.


How to Get One File From Another Branch in Git

Here are the steps to get one file from another branch in git.

First, you need to switch to the branch where you want to copy the desired file. Here is an example where we switch to master branch.

$ git checkout master

Next, use git checkout command to copy the file (e.g. data.txt) from the source branch to your present branch. Here is an example to copy this file from test branch.

$ git checkout test -- data.txt

If you are using git>2.23, you can also use git switch and git restore commands.

$ git switch master
$ git restore --source test -- data.txt

The above commands will restore only the latest version of file in the specified branch. If you want to checkout a specific revision of a file, you can use the following command. Replace $REVISION with the commit hash whose file version you want to copy, and $FILENAME with the file path of the file to be copied.

$ git show $REVISION:$FILENAME
OR
$ git checkout $REVISION -- $FILENAME

In this article, we we have learnt how to get one file from another branch to your present working branch.

Also read:

How to Change Git Commit Message
How to Force Git Pull to Overwrite Local Files
How to Delete Git Branch Locally & Remotely
How to Reset or Revert File to Specific Commit in Git
How to Find & Restore Deleted File in Git Repository

Leave a Reply

Your email address will not be published. Required fields are marked *