Synchronizing a local Git repository with a remote one

Viewed 620926

I want to synchronize my local repository with a remote one so that my local repository becomes a 100% copy of the remote one - meaning that if certain files differ in these repositories, we override the local ones with the remote ones, and if there are files in local repositories that do not exist in the remote, the local files get removed.

Is there any way to achieve that other than by doing a fresh clone of remote repository?

Similar question as Sync local git repo with remote in one shot discarding local changes/commits.

11 Answers

Reset and sync local repository with remote branch

The command: Remember to replace origin and master with the remote and branch that you want to synchronize with.

git fetch origin && git reset --hard origin/master && git clean -f -d

Or step-by-step:

git fetch origin
git reset --hard origin/master
git clean -f -d

Your local branch is now an exact copy (commits and all) of the remote branch.

Command output:

Here is an example of running the command on a local clone of the Forge a git repository.

sharkbook:forge lbaxter$ git fetch origin && git reset --hard origin/master && git clean -f -d
HEAD is now at 356cd85 FORGE-680
Removing forge-example-plugin/
Removing plugin-container-api/
Removing plugin-container/
Removing shell/.forge_settings
sharkbook:forge lbaxter$

The permanent fix if one wants to create a new branch on the remote to mirror and track your local branch(or, vice-versa) is:

git config --global push.default current

I always configure my local git with this command after I do git clone. Although it can be applied anytime when the local-remote branch "Git fatal: The current branch has no upstream branch" error occurs.

This script will check what local remotes do not exist in your remote and remove them from local

git fetch --prune; git branch -vv | egrep -v "(\[origin\/[a-zA-Z0-9/_-]+\])" | awk "{print \$1}" | xargs git branch -D
Related