Skip to content

Copy file from another branch using git checkout

Posted on:May 10, 2024 at 03:22 PM

How to copy a file from another branch using git checkout

git checkout is a versatile command in Git used primarily for switching between branches, creating branches, and reverting changes in your working directory.

One of its lesser know feature is copying content of a file from another branch. This can be done via following command: git checkout branch -- filename

Here’s what each part of the command does:

So, when you run git checkout branch -- filename, Git replaces the filename in your current working directory with the version of filename from the specified branch, effectively overwriting any changes you might have made to filename in your current working directory.

Bonus uses

Discard Changes in Working Directory:

git checkout -- <file_name>

This discards the changes made to a specific file in the working directory and reverts it to the state it was in the last commit. Example:

git checkout -- index.html

Discard All Changes in Working Directory:

git checkout -- .

This discards all changes made to tracked files in the working directory and reverts them to the state they were in the last commit.

Create a New Branch from a Remote Branch:

git checkout -b <new_branch_name> <remote_name>/<branch_name>

This creates a new branch from a remote branch and switches to it. Example:

git checkout -b hotfix origin/main