Table of Contents
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.
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.
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.
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
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
You can also use the
git restore command to achieve the same:
1git restore --source secondary file-two.txt
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.
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.txt23# OR45git restore --source main file-two.txt67# OR89git show main:file-two.txt>file-two.txt
If you want to experiment, you can clone the repository from here.
If you have liked article, do follow me on twitter to get more real time updates!