Merge and Pull in Git
Merge
Merge is a command used to combine the changes from one branch into another. It is typically used to integrate changes from a feature branch back into the main branch (e.g., main
or master
).
- Merging a Branch
git checkout main
git merge my-feature-branch
- This command switches to the
main
branch and merges the changes frommy-feature-branch
intomain
.
Fetch + Merge = Pull
Pull is a command that combines fetch
and merge
. It is used to update your local branch with changes from a remote branch.\\
Fetch:
- The
git fetch
command downloads commits, files, and refs from a remote repository into your local repository. It updates your remote-tracking branches but does not merge changes into your local branches.
git fetch origin
Merge:
- After fetching, you can merge the changes into your local branch.
git merge origin/main
Pull:
- The
git pull
command is a combination offetch
andmerge
. It fetches changes from the remote branch and automatically merges them into your current local branch.
git pull origin main
Example Workflow
Scenario: Working with Local and Remote Branches
Clone a Repository:
git clone https://github.com/your-username/your-repo.git
cd your-repo
Create and Switch to a New Local Branch:
git checkout -b my-feature-branch
Make Changes and Commit:
# Make changes to your files
git add .
git commit -m "Add new feature"
Push the Local Branch to Remote:
git push origin my-feature-branch
Create a Pull Request on GitHub:
- Go to your repository on GitHub.
- Create a pull request to merge
my-feature-branch
intomain
.
Fetch and Merge Changes from Remote:
git fetch origin
git checkout main
git merge origin/main
Alternatively, Pull Changes from Remote:
git pull origin main
- Merge: Combines changes from one branch into another.
- Fetch: Downloads changes from a remote repository without merging them.
- Pull: Combines
fetch
andmerge
to update your local branch with changes from a remote branch.