Creating a new branch and merging it into another branch is a common workflow in Git. This guide will walk you through the steps to create a branch, make changes, and merge those changes back into the main branch.
Step 1: Check Out the Base Branch
Before creating a new branch, ensure you’re on the branch you want to base it on (e.g., `development`):
git checkout development
Step 2: Create a New Branch
To create a new branch, use the following command:
git checkout -b feature-branch-name
This creates and switches to the new branch, feature-branch-name
.
Step 3: Make Changes and Commit
After creating the branch, make your changes, then stage and commit them:
git add .
git commit -m "Add feature or changes description"
Step 4: Push the Branch to Remote
Push your new branch to the remote repository so others can access it:
git push origin feature-branch-name
Sets the upstream tracking branch (so future git pull
or git push
commands work seamlessly):
git push --set-upstream origin feature-branch-name
Step 5: Merge the New Branch
Once your work is complete and reviewed, merge the branch back into the base branch (e.g., development
).
a. Switch to the Base Branch:
git checkout development
b. Pull the Latest Changes (Optional but Recommended):
git pull origin development
c. Merge the New Branch:
git merge feature-branch-name
Step 6: Delete the Feature Branch (Optional)
After merging, you can delete the branch to keep the repository clean.
Locally:
git branch -d feature-branch-name
Remotely:
git push origin --delete feature-branch-name
Key Points to Remember
- Always base your new branch on the most recent version of the base branch.
- Resolve merge conflicts carefully during the merge process.
- Test thoroughly before merging to ensure the changes don’t break anything.
By following these steps, you can manage branches effectively and streamline your Git workflow. If you have any questions, feel free to leave a comment!