Introduction
🧑💻 New to Git or LabEx? We recommend starting with the Quick Start with Git course.
Git is a powerful version control system that allows developers to manage their codebase efficiently. One of the most useful features of Git is the ability to cherry-pick changes from one or more commits. This allows developers to apply specific changes to their codebase without having to merge entire branches.
Git Cherry-Pick
As a developer, you are working on a project with multiple branches. You have identified a specific change that was made in a previous commit that you would like to apply to your current branch. However, you do not want to merge the entire branch as it contains other changes that you do not need. In this scenario, you can use the git cherry-pick command to apply the specific change to your current branch.
For this lab, let's use the repository from https://github.com/labex-labs/git-playground. Follow the steps below to complete the challenge:
- Clone the repository, navigate to the directory and configure the identity:
git clone https://github.com/labex-labs/git-playground
cd git-playground
git config --global user.name "your-username"
git config --global user.email "your-email"
- Create and switch to a branch called
one-branch, create a file calledhello.txt, write "hello,world" in it, add it to the staging area and commit it with the message "add hello.txt":
git checkout -b one-branch
echo "hello,world" > hello.txt
git add .
git commit -m "add hello.txt"
- Identify the hash of the commit created in the previous step to apply to the
masterbranch:
git log
- Checkout the
masterbranch and apply the change to themasterbranch:
git checkout master
git cherry-pick 1609c283ec86ee4
- Verify that the change has been applied to the
masterbranch:
git log
This is the result of running git log on the master branch:
ADD hello.txt
Summary
In this lab, you learned how to use the git cherry-pick command to apply specific changes from one or more commits to your current branch. This is a powerful feature of Git that allows developers to manage their codebase efficiently and avoid merging entire branches.