Once you’ve connected your local repository to a remote server (like GitHub) using git remote add origin, you need commands to exchange data between them. This process is crucial for collaboration and project backup.
1. Uploading Changes (git push)
The git push command is used to upload your local commits to the specified remote repository, making your changes available to others.
Initial Push (Setting Upstream)
The very first time you push a new local branch (like main or a feature branch), you must specify the remote name (usually origin) and the branch name. You should also include the --set-upstream (or -u) flag.
- Purpose of
-u: This links your local branch to the remote branch, so for all future pushes and pulls on that branch, you can just typegit pushorgit pull.
Execution Example: First Push
Assuming you are on the main branch:
git push -u origin main
Subsequent Pushes
After the upstream tracking is set up, you only need the short command:
git push
2. Downloading Changes (git fetch)
The git fetch command downloads the latest changes and commit history from the remote repository to your local machine.
- Crucial Point:
git fetchupdates the local copy of the remote branch (e.g.,origin/main), but it does not merge those changes into your current local working branch.
Execution
git fetch origin
After running this, you can use git log or git diff to inspect the new commits before deciding to merge them into your working code.
3. Fetching and Merging (git pull)
The git pull command is a combination of two operations in one step:
git fetch: Downloads changes from the remote.git merge: Immediately merges those downloaded changes into your current local branch.
Execution
When on your local main branch, to synchronize with the remote origin/main:
git pull origin main
Or, if upstream tracking is set:
git pull
Best Practice: Always commit or stash your local work before running
git pullto avoid unexpected conflicts between your current working files and the incoming changes.
4. Cloning a Remote Repository (Review)
As a reminder from Chapter G8, if the project doesn’t exist locally, you start with git clone.
Execution
This command initializes the repository, sets the origin remote, and automatically runs git pull to get all files.
git clone git@github.com:username/repo.git
