How to Copy File From Another Branch in Git

Abdul Jabbar Feb 02, 2024
How to Copy File From Another Branch in Git

In Git, merging various files can cause many conflicts. By these merge conflicts, our files may be in harm, so we must copy those files or folders from one branch into another to keep them safe.

One of the popular methods is Cherry Picking. But if we don’t want to execute this method, we have a better method: git checkout from the remote branch.

Copy File From Another Branch in Git Using the git checkout Command

The git checkout command is used to change the branches and restore the files in the working tree. It is used to operate files, folders, and commits also.

This article will show how to use the git checkout command to copy single or multiple folders or files from one branch to another without merging the whole branch with other branches.

The following are the command through which we can copy files from other branches. It depends on where we want to take a file from (a local branch, a commit, or a remote branch).

We can check through the command git status on which branch we are.

git status

After, we will create a file and commit it to another branch.

git checkout -b new_branch

git add test.txt

git commit -m "Create test"

Now, we will switch again to the master branch.

git checkout master

We will check out the file from the other branch to copy the file.

git checkout new_branch test.txt

Finally, our file is copied successfully to our current branch. So, we can check it using the following command.

git status

Copy One or More Files From Another Branch in Git Using the git checkout Command

For single or multiple files, we will run the following command:

git checkout <other-branch-name> -- path/to/your/file.

Copy Folder From Another Branch in Git Using the git checkout Command

To copy the whole folder into our current branch, we will execute the following command:

git checkout <other-branch-name> -- path/to/your/folder

Copy Files and Folders From Commit of Another Branch Using the git checkout Command

To copy some files or folders from a specific commit of another branch, we will run this command:

git checkout <commit_hash> <relative_path_to_file_or_dir>
Author: Abdul Jabbar
Abdul Jabbar avatar Abdul Jabbar avatar

Abdul is a software engineer with an architect background and a passion for full-stack web development with eight years of professional experience in analysis, design, development, implementation, performance tuning, and implementation of business applications.

LinkedIn

Related Article - Git Branch