Pushing and Pulling Code: git push -u origin main and git pull
Pushing and Pulling Code: git push -u origin main and git pull
Once your local repository is connected to a remote on GitHub, you transfer commits back and forth using git push (uploading local changes to the cloud) and git pull (downloading cloud updates into your local machine).
1. Pushing Code: git push
The git push command exports commits from your local repository to a branch on the remote server.
The First Push: Setting Upstream Tracking (-u)
The very first time you push a newly created branch to a remote, you must tell Git which remote branch should track your local branch:
What does the -u (or --set-upstream) flag do?
- It binds your local
mainbranch to the remote branchorigin/main. - For all future pushes and pulls on this branch, you no longer need to type
origin main. You can simply type:
Terminal Output:
2. Pulling Code: git pull vs. git fetch
When working in a team or across multiple computers, teammates will push new commits to GitHub. You must pull these commits down to stay updated.
Deep Dive: What is git pull Really Doing?
git pull is actually a combination of two underlying Git commands:
- 1
git fetch: Downloads all commits, branches, and tags from the remote repository into your local.gitfolder, updating remote-tracking branches (likeorigin/main), but leaves your working directory untouched. - 2
git merge origin/main: Integrates the fetched commits into your active local branch.
Or execute both in one command:
3. Dealing with Rejected Pushes (Non-Fast-Forward)
If a colleague pushed commits to GitHub while you were working locally, GitHub will reject your push with:
The Standard Fix:
- 1Pull the colleague's commits down to your local machine:
- 1If there are merge conflicts, resolve them and commit.
- 2Now push your combined work cleanly:
git push --force on shared production branches! Force-pushing overwrites and deletes your teammates' commits from the remote server.Practice Quiz
git push -u origin main accomplish?git pull?git fetch differ from git pull?(fetch first) non-fast-forward error?git push --force strongly discouraged on shared collaborative branches?Forking Repositories and Cloning to Local Machine (git clone)
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.