DEV Community

Geoffrey Kim
Geoffrey Kim

Posted on

Moving Work from the Main Branch to a New Branch in Git

As developers, we sometimes find ourselves working on the main branch without realizing it. This can be problematic if we want to keep the main branch clean or if we need to create a separate feature branch for our work. Fortunately, Git provides an easy way to move your work from the main branch to a new branch. Here’s a step-by-step guide on how to do this.

Step 1: Commit Your Current Work on the Main Branch

Before creating a new branch, ensure that your current work on the main branch is committed. This step is crucial because any uncommitted changes might be lost during the branch switch.

Open your terminal and run the following commands:

git add .
git commit -m "Commit message describing your work"
Enter fullscreen mode Exit fullscreen mode

Step 2: Create and Switch to a New Branch

Next, you need to create a new branch and switch to it. You can do this using a single command. Here, I’ll use new-branch as the example branch name. Replace it with your preferred branch name.

git checkout -b new-branch
Enter fullscreen mode Exit fullscreen mode

This command does two things:

  1. Creates a new branch named new-branch.
  2. Switches your working directory to the newly created branch.

Step 3: Push the New Branch to the Remote Repository

Now that you’re on the new branch, it’s time to push it to the remote repository. This will ensure that your work is safely backed up and can be accessed by your team.

git push origin new-branch
Enter fullscreen mode Exit fullscreen mode

Step 4 (Optional): Reset the Main Branch to Its Original State

If you want to revert the main branch to its original state (i.e., before you started your work), you can do so with the following commands. Be cautious with this step, as it will remove all the changes you made on the main branch.

First, switch back to the main branch:

git checkout main
Enter fullscreen mode Exit fullscreen mode

Then, reset the main branch to match the remote repository:

git reset --hard origin/main
Enter fullscreen mode Exit fullscreen mode

Step 5 (Optional): Keep Your Changes in the Main Branch

If you decide to keep your changes in the main branch as well, you can skip the reset step. This way, your changes will exist in both the main branch and the new branch.

Conclusion

By following these steps, you can easily move your work from the main branch to a new branch in Git. This practice helps in maintaining a clean main branch and enables better collaboration within your team. Remember, committing your work regularly and creating feature branches for new tasks are good habits that can save you from potential headaches in the future.

Top comments (0)