W3docs

How to Copy a Version of a Single File from One Git Branch to Another

orial and find several solutions to the problem of copying a version of a single file from one branch to another. Also, read important tips.

Merge conflicts occur frequently, and sometimes you need to take steps to preserve your work. If a file is overwritten by merge conflicts, it is easier to replace it with the version from another branch, then stage and commit the changes. Let's see how to do that.

Copying a Version of a File Using git checkout

You can execute one of the following commands, depending on where you want to take a file from (a local branch, a commit, or a remote branch):

From a local branch

git checkout

git checkout <other-branch-name> <file-or-dir>

From a commit

git checkout

git checkout <commit-hash> <file-or-dir>

From a remote branch

git checkout

git checkout <remote-name>/<branch-name> <file-or-dir>

Keep these tips in mind: using a commit hash allows you to retrieve files from any point in history. Wildcards also work if wrapped in single quotes to prevent shell interpretation. After running either command, remember to stage the file with git add <file> and commit it to finalize the change.

Copying a Version of a File Using git show

Another solution is running <kbd class="highlighted">git show</kbd>:

git show

git show commit-hash:path/to/file > path/to/file

The git checkout Command

The primary role of git checkout is switching branches or restoring working tree files. The command updates the files in the working directory to match the version stored in the specified branch or commit. Note that git checkout only updates the working tree and index; you must still run git add and git commit to record the changes.

The <kbd class="highlighted">git checkout</kbd> command is often used alongside git branch and git clone. While git clone fetches code from a remote repository, git checkout switches between code versions on the local system.

Note: Since Git 2.23, git restore is the recommended command for restoring files. Use git restore --source=<branch> <file> as a modern alternative to git checkout.