Synchronizing a local Git repository with a remote one

Question

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.

Answer

[Edited answer] There is a few parts to consider:

While not really operating a 'full sync' with the remote, the following will probably achieve what you need.

Note: you may lose local changes.

The Branch references

When fetching from a repository, the new (remote) references are synced up automatically but the old ones aren't cleaned out from the local. The purge option fixes that. [original answer]

git fetch --prune

-p, --prune
Before fetching, remove any remote-tracking references that no longer exist on the remote. git fetch prune option doc on git-scm

The pull command also has the prune option (--prune or -p) see git-scm doc

git pull -p

The commits

All local branches could potentially be out of sync.

To sync up the current branch with the remote, and potentially lose local work, reset it to the remote position:

git reset --hard origin/<current_branch_name>

Again, caution: this would clear out the local changes (non-committed changes & non-pushed commits).

Note: This would have left 'un-synced' any other branch.

The files/changes

The not staged for commit changes

These would have been removed by the above git reset --hard

The untracked files

These can be cleaned out using

git clean -f -d

Note that you may lose some local work.

The ignored files

Some files are declared to be ignored (via .gitignore files) and become hidden to the git tracking.

To clean them out, run:

git clean -f -d -x

Note that the git clean command comes with a handy dry-run option to avoid making that mistake a little too fast:

git clean -f -d -x -n

-n, --dry-run

Don’t actually remove anything, just show what would be done.


As the top-rated answer, I felt compelled to revisit my not really answering former reply. Thanks to the comments and other answers which helped me form a better reply.

How to list branches that contain a given commit?

Git - remote: Repository not found