Step-by-Step Guide: Using Git Cherry-Pick to Apply Specific Commits Across Branches

Step-by-Step Guide: Using Git Cherry-Pick to Apply Specific Commits Across Branches

ยท

2 min read

Step 1: Create a Git Repository

First, let's create a new Git repository and initialize it:

mkdir my-git-repo
cd my-git-repo
echo "# githubcherry" >> README.md
git init
git add README.md
git commit -m "first commit"
git branch -M master

Step 2: Create and Switch to Branches

Create multiple branches and switch between them. For this example, we will create three branches: feature-branch1, feature-branch2, and master.

git checkout -b feature-branch1

echo "New feature" > feature.txt
git add feature.txt
git commit -m "Feature 1: Commit 1"

git checkout -b feature-branch2
echo "New update" > update.txt
git add update.txt
git commit -m "update 2: Commit 1"

Step 3: Cherry-pick Commits

Let's assume you want to cherry-pick a commit from feature-branch1 into master. First, find the commit hash of the specific commit you want to pick:

git log

Now, let's cherry-pick the commit into master:

git checkout master
git cherry-pick <commit-hash-from-feature-branch1>

Repeat the cherry-pick process for any other commits you want to transfer between branches.

Step 4: Resolve Conflicts (if any)

If there are any conflicts during the cherry-pick process, Git will pause and ask you to resolve them. Open the conflicted file(s), manually resolve the conflicts, save the changes, and then continue the cherry-pick process:

git cherry-pick --continue

Step 6: Verify the Changes

You can use git log and inspect the files to verify that the cherry-picked changes are now in feature-branch.

Step 5: Commit the Cherry-Picked Changes

After resolving conflicts (if any), Git will create a new commit with the changes from feature-branch1 applied to feature-branch2. You can commit this new change:

git commit -m "Cherry-picked changes from feature-branch1"

That's it! We have successfully created a Git repository with multiple branches, used git cherry-pick to apply specific commits from one branch to another, and committed the changes.

Did you find this article valuable?

Support Edvin Dsouza by becoming a sponsor. Any amount is appreciated!

ย