How to Push and Pull Code

How to Push and Pull Code

Pulling updates from a remote repository

git pull updates your current local working branch with all new commits from the corresponding remote branch. It is a combination of git fetch and git merge.

Run git pull regularly — at minimum every day you interact with a repository that has a remote.

Before you pull, run git status first. Changes that are not committed can be overwritten during a git pull, or they can block the merge from completing.

Common options:

  1. git pull — update your local working branch with commits from the remote, and update all remote tracking branches.
  2. git pull --rebase — same as above, but rewrites history so your local commits appear after all new commits from the remote, avoiding a merge commit.
  3. git pull --force — force a fetch of a specific remote tracking branch when there are conflicts with the <refspec> option.
  4. git pull --all — fetch all remotes, useful when working with a fork or multiple remotes.

Pushing local changes to GitHub

git push uploads all local branch commits to the corresponding remote branch. By default, it only updates the branch you are currently checked out to.

Best practice: Run git pull before pushing. This reduces merge conflicts by letting you resolve them locally first.

Common options:

  1. git push — push commits on the current branch to its remote counterpart.
  2. git push -u origin [branch] — use this when pushing a new branch; it creates an upstream tracking relationship between the local and remote branch.
  3. git push -f — force a push that would otherwise be blocked. Use with caution, as it can delete or overwrite existing commits.
  4. git push --all — push all branches.
  5. git push --tags — publish tags that are not yet in the remote repository.

Can't push? Common fixes

  • Check your current branch with git status. If you are on a protected branch like main, direct pushes may be blocked.
  • If you committed to the wrong branch, checkout the intended branch, merge in your commits, and then push.
  • To push a new branch, use git checkout -b [branchname] and then git push -u origin [branchname].

Source: https://github.com/git-guides/git-push, https://github.com/git-guides/git-pull

Related articles