Pushing & Pulling from GitHub & GitLab – Syncing Your Repositories
Why Pushing & Pulling is Important?
When working with Git, you need to sync your local repository with a remote repository (e.g., GitHub or GitLab) so that your changes are saved, shared, and up-to-date.
This guide will help you understand: ✅ How to push commits to a remote repository.
✅ How to pull updates from a remote repository.
✅ The difference between git pull
and git fetch
.
✅ How to handle conflicts when pulling changes.
Pushing Changes to a Remote Repository
Once you have made changes and committed them locally, push them to a remote repository to share them with others.
Push Changes to the Default Remote Branch
If your repository is already connected to a remote repository, push changes using:
git push
This command pushes changes to the remote repository and updates the corresponding branch.
Push Changes to a Specific Branch
If you need to push to a specific branch, use:
git push origin <branch-name>
Example:
git push origin feature-branch
Setting the Upstream Branch (For New Branches)
If you created a new branch and are pushing it for the first time, use:
git push --set-upstream origin <branch-name>
This sets up a tracking connection between your local and remote branch.
Pulling Changes from a Remote Repository
If other contributors have made changes, you need to fetch the latest updates before making further modifications.
Pull Updates from the Default Remote Branch
To download and merge the latest changes:
git pull
This command fetches new changes from the remote repository and merges them into your current branch.
Pull from a Specific Branch
To pull changes from a specific branch:
git pull origin <branch-name>
Example:
git pull origin main
Fetching Changes Without Merging
If you want to check for updates without immediately merging them, use:
git fetch
This retrieves new changes from the remote repository without modifying your local code. You can then manually merge the changes if needed.
To see what changes have been fetched:
git log origin/main --oneline
⚠ Handling Merge Conflicts When Pulling
If changes in the remote repository conflict with your local changes, Git will warn you about a merge conflict.
Steps to Resolve Merge Conflicts
1️⃣ Git will show the files with conflicts:
git status
2️⃣ Open the affected files and manually edit the conflicting sections. 3️⃣ After resolving conflicts, stage the file:
git add <file-name>
4️⃣ Complete the merge by committing the resolved changes:
git commit -m "Resolved merge conflict in <file-name>"
Next Steps
Now that you know how to push and pull changes, explore more Git topics:
Git Branching & Merging – Learn how to create and manage branches.
Undoing Mistakes in Git – Recover from common Git errors.
Need help? Check the official Git documentation or ask in the comments!