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

Merge conflicts occur very often and, sometimes, you have to undertake some steps to save your work. If your file has been messed up by merge conflicts, then it is easier to change it to the new version from another branch, and insert the changes after bringing into your branch. Let's see how to do that.

Watch a course Git & GitHub - The Practical Guide

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 <other-branch-name> <file-or-dir>

From a commit

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

From a remote branch

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

Here you should remember some important tips to make your work done properly. Using the commit hash makes it possible to pull files from any commit. Wildcards also work if you wrap them in single quotes, so they do not get interpreted by the shell.

Copying a Version of a File Using git show

Another solution is running 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. Thus, it operates on files, commits, and branches. The command updates the files in the working directory so as to match the version stored in that branch, instructing Git to record all the new commits.

The git checkout command works hand in hand with another important git command: git branch. It is more often associated with git clone. The git clone command operates to fetch code from a remote repository, whereas git checkout works to switch code versions on the local system.