Data report"State of code review 2024" is now liveRead the full report

How to copy a branch in git

Kenny DuMez
Kenny DuMez
Graphite software engineer


Note

This guide explains this concept in vanilla Git. For Graphite documentation, see our CLI docs.


Copying a branch in Git requires different approaches depending on what you want to achieve, whether it's duplicating a branch, copying files between branches, or transferring specific changes from one branch to another. This guide will cover each of these scenarios in detail, providing clear examples to help you manage your branches.

To copy a branch in Git means creating a new branch that points to the same commit as the existing branch. This is useful for creating feature branches from a development branch or duplicating a branch for testing purposes.

Step 1: Checkout the branch you want to copy

First, switch to the branch that you want to copy:

Terminal
git checkout <source_branch>

Step 2: Create a new branch

Then, create a new branch from the current branch:

Terminal
git checkout -b <new_branch_name>

This command makes <new_branch_name> a direct copy of <source_branch>.

If you only need to copy a specific file or set of files from one branch to another, use the following steps:

Step 1: Checkout the target branch

Switch to the branch where you want the file to go:

Terminal
git checkout <target_branch>

Step 2: Copy the file from the source branch

Copy the file from another branch without switching branches:

Terminal
git checkout <source_branch> -- <path_to_file>

This command brings the specific file from <source_branch> into your current working directory on <target_branch>.

Step 3: Commit the changes

After copying the file, commit it to the target branch:

Terminal
git add <path_to_file>
git commit -m "Copied <path_to_file> from <source_branch> to <target_branch>"

To copy specific commits or changes from one branch to another, you can use the git cherry-pick command. This is useful for applying bug fixes or feature additions selectively.

Step 1: Find the commit hash

First, identify the commit(s) you want to copy. You can find the commit hash by looking at the log of the source branch:

Terminal
git log <source_branch>

Step 2: Cherry-pick the commit

Switch to the target branch where you want to apply the commit:

Terminal
git checkout <target_branch>

Then cherry-pick the commit:

Terminal
git cherry-pick <commit_hash>

If there are conflicts, Git will prompt you to resolve them before completing the cherry-pick.

For further reading on Git branching, see the official Git documentation.

Git gud
"It's the first Git workflow I've used that actually feels good."
–@robboclancy
Learn more

Graphite
Git stacked on GitHub

Stacked pull requests are easier to read, easier to write, and easier to manage.
Teams that stack ship better software, faster.

Or install our CLI.
Product Screenshot 1
Product Screenshot 2