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 challenge, 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-12656{{"`Move Commits to a New Branch`"}} end

Move Commits to a New Branch

For this challenge, 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.

Tasks

  1. Navigate to the repository directory and configure your GitHub identity.
  2. Checkout the master branch.
  3. 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".
  4. Create a new branch called feature without switching to it .
  5. Undo the last commit on master.
  6. Check the commit history on the master branch and the commit history on the feature branch to verify the results.

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 challenge, 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