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 keep track of changes made to their codebase. One of the useful features of Git is the ability to move commits from one branch to another. This can be helpful when you realize that some changes you made to the master branch should have been made on a separate branch. In this lab, you will learn how to move commits from the master branch to a new branch.
Move Commits to a New Branch
For this lab, let's use the repository from https://github.com/labex-labs/git-playground. You have been working on a project in the master branch. You realize that some of the changes you made should have been made on a separate branch. You want to move these changes to a new branch called feature.
- 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"
- Checkout the
masterbranch:
git checkout master
- Create a file called
hello.txt, add "hello, world" to it, add it to the staging area and submit it with the message "Added hello.txt":
echo "hello,world" >> hello.txt
git add .
git commit -m "Added hello.txt"
- Create a new branch called
featurewithout switching to it. When you create a new branch on themasterbranch, the state of the new branch is the same as themasterbranch, i.e., the files in the new branch are the same as the files in themasterbranch, with the same content and version history:
git branch feature
- Undo the last commit on
master:
git reset HEAD~1 --hard
- Check the commit history on the
masterbranch and the commit history on thefeaturebranch to verify the results:
git log
git checkout feature
git log
This is the result of running git log:
commit 7969ab5d6606e2a40c9fd826c732206b835976e9 (HEAD -> feature)
Author: xiaoshengyunan <@users.noreply.github.com>
Date: Fri Jul 21 20:19:22 2023 +0800
Added hello.txt
Summary
Moving commits from one branch to another can be a helpful feature when working with Git. In this lab, you learned how to move commits from the master branch to a new branch using git branch, git reset, and git checkout commands. Remember that this only works if the changes have only been committed locally and not pushed to the remote.