GitHub Tutorial
- 1. Introduction to GitHub
- 2. Account Setup & SSH
- 3. Repository Management
- 4. Remotes & Syncing
- 5. Collaborating Via Branches
- 6. Forking & Pull Requests
- 7. Code Reviews & Branch Protection
- 8. Merge Strategies
- 9. Issues & Projects
- 10. Markdown & Project Wikis
- 11. Deploying to GitHub Pages
- 12. CI/CD with GitHub Actions
- 13. Packages & Releases
- 14. Gists & Discussions
- 15. Security & Dependabot
4. Remotes & Syncing
Once you have a local Git repository on your machine and an empty repository hosted on GitHub, you need to connect them. In this chapter, we will learn how to add remotes, synchronize histories, and establish upstream tracking.
1. Linking Local and Remote Repositories
When you create an empty repository on GitHub, it will display a page showing a set of setup terminal commands. To link an existing local repository to this remote, run:
git remote add origin git@github.com:username/repo-name.gitLet's break down this command:
git remote add: Adds a new remote reference to your local config.origin: The alias name for the remote. By convention, the primary remote is always named "origin".git@github.com:username/repo-name.git: The SSH URL of your GitHub repository.
2. Verifying Remote Connections
To verify that your local repository has successfully saved the remote address, run:
git remote -vThis should print two lines (one for fetching, one for pushing):
origin git@github.com:username/repo-name.git (fetch)
origin git@github.com:username/repo-name.git (push)3. Pushing to GitHub: The -u Upstream Flag
The first time you upload commits from your local default branch (e.g., main) to GitHub, you need to specify the remote name and the branch. We also include the -u flag:
git push -u origin mainThe -u (or --set-upstream) flag tells Git to remember the connection between your local main branch and the main branch on the origin server. Once this upstream tracking is established, you no longer need to type the full command! For all future syncs, simply type:
git push4. Fetching vs. Pulling
When collaborating on GitHub, other developers will push changes to the repository. To sync your local machine with those cloud changes, you have two operations:
A. Fetching: git fetch
Downloads all branches, commits, and tags from GitHub, but does **not** merge them into your local files. It is a safe, non-destructive read-only operation:
git fetch originB. Pulling: git pull
Downloads remote changes and immediately merges them into your active branch:
git pull origin maingit pull --rebase origin main5. Renaming a Remote Reference
If you ever need to change the URL of your remote server (for example, if you move your project from Bitbucket to GitHub):
git remote set-url origin git@github.com:username/new-repo-name.git