Skip to content
git

How to checkout a file from another branch in git

Jul 16, 2022Abhishek EH3 Min Read
How to checkout a file from another branch in git

You might have switched branches and checked out another branch in git using the command git checkout <branch_name>. After checking out the entire branch have you realized that you just wanted to see only one file and wanted to have other files from the original branch? In this article, we will discuss how to achieve the same.

Creating a git repo with 2 branches

First, let's create a git repo for demonstrating the use case.

Create an empty directory named git-checkout-file-example.

Create a couple of files inside it with the following content.

file-one.txt
1file-one-main
file-two.txt
1file-two-main

Now run the command git init to initialize the git repository. You will need git installed in your machine for the command to work.

Once the repository is initialized, run the following command to stage and commit the files.

1git add .
2git commit -m "First commit"

Now create a new branch called secondary using the below command:

1git branch secondary

Check out the newly created branch:

1git checkout secondary

Now update the files to ensure that we have checked out (in the next section) the right file.

file-one.txt
1file-one-secondary
file-two.txt
1file-two-secondary

Stage and commit the changes.

1git add .
2git commit -m "Second commit"

Now switch back to the original branch by running the following command (change to master, if that's your initial branch).

1git checkout main

Checking out a single file from another branch

Using git checkout

You can checkout a file from another branch using the syntax git checkout <branch_name> -- <path_to_file>

In our example,

1git checkout secondary -- file-two.txt

Using git restore

You can also use the git restore command to achieve the same:

1git restore --source secondary file-two.txt

Using git show

We can also use the git show command to checkout a single file:

1git show secondary:file-two.txt>file-two.txt

Here you need to specify the destination file name as well. This will help if you need to checkout the contents to a different file name for comparison purposes.

Reverting the checkout

If you want to revert the checkout you made, you can do so by running the same command on the original branch.

1git checkout main -- file-two.txt
2
3# OR
4
5git restore --source main file-two.txt
6
7# OR
8
9git show main:file-two.txt>file-two.txt

The repository

If you want to experiment, you can clone the repository from here.

Do follow me on twitter where I post developer insights more often!

Leave a Comment

© 2024 CodingDeft.Com