Move the Most Recent Commit(s) to a New Branch with Git
To move the most recent commit(s) to a new branch in Git, you can use the following steps:
Step 1: Create a New Branch
First, create a new branch at the current commit:
git branch new-branch-name
This command creates a new branch named new-branch-name
that points to the current commit.
Step 2: Switch to the New Branch
Switch to the newly created branch:
git checkout new-branch-name
Or, if you're using Git version 2.23 or later, you can combine steps 1 and 2 using the -b
option:
git checkout -b new-branch-name
This command creates a new branch named new-branch-name
and switches to it.
Step 3: Reset the Original Branch
Now, reset the original branch (the one you were previously on) to the commit before the one you want to move:
git reset --hard HEAD~1
This command moves the HEAD of the original branch to the previous commit (HEAD~1
) and discards any changes made in the most recent commit.
Note:
- Be careful when using
git reset --hard
, as it will discard any changes made in the most recent commit(s) and reset the working directory to the state of the specified commit. - If you have multiple recent commits to move to the new branch, you can adjust the number in the
HEAD~1
command to match the number of commits you want to move (HEAD~2
,HEAD~3
, etc.).
-
What Is the Difference between ‘Git Pull’ and ‘Git Fetch’?
git pull and git fetch are both Git commands used to update your local repository with changes from a remote repository. However, they work differently.
Questions -
How Do I Revert a Git Repository to a Previous Commit?
To revert a Git repository to a previous commit, you have a couple of options depending on your needs. Here are two common methods: Method 1: Using git reset and git push (For Local Changes Only) I...
Questions -
How Do I Force “Git Pull” to Overwrite Local Files?
To force git pull to overwrite local files, you can use the git reset command along with the --hard option after pulling changes. Here's how you can do it: Step 1: Pull Changes from Remote First, p...
Questions
Make your mark
Join the writer's program
Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.
Write for usBuild on top of Better Stack
Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.
community@betterstack.comor submit a pull request and help us build better products for everyone.
See the full list of amazing projects on github