Move Commits to a New Branch

GitGitBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL git(("`Git`")) -.-> git/BranchManagementGroup(["`Branch Management`"]) git/BranchManagementGroup -.-> git/branch("`Handle Branches`") subgraph Lab Skills git/branch -.-> lab-12742{{"`Move Commits to a New Branch`"}} end

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.

  1. 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"
  1. Checkout the master branch:
git checkout master
  1. 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"
  1. Create a new branch called feature without switching to it. When you create a new branch on the master branch, the state of the new branch is the same as the master branch, i.e., the files in the new branch are the same as the files in the master branch, with the same content and version history:
git branch feature
  1. Undo the last commit on master:
git reset HEAD~1 --hard
  1. Check the commit history on the master branch and the commit history on the feature branch 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.

Other Git Tutorials you may like