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:
git checkout
: This part of the command is a bit misleading, normally this is used to switch between brances, create branch.branch
: This is the name of the branch from which you want to take the version of the file.--
: This is an optional separator that indicates the end of the branch name and the beginning of the filenames. It’s used to avoid ambiguity in case the branch name is similar to a filename.filename
: This is the name of the file you want to overwrite with the version from the specified branch.
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