Ovewriting an existing Gibhub Repo with another Git Repo

How to force change your local git repo to an existing github repo

Edgar
Edgar  

Photo by Yancy Min (opens new window) on Unsplash (opens new window)

There are many resources on the basics of using Git with Github. I highly recommend when coding to use git to control your code to manage changes and revert if needed.

However, in my travels on the internet, it is more difficult to find a tutorial on how to replace an existing git repository with another. This may happen if you clone a github repo and you want to replace your existing git repo with the cloned repo.

I am assuming that you have installed git and have an account on github.com (opens new window). I am also assuming the main branch is called 'main' (Older github repos are likely to be called 'master'). On your local machine, I am also assuming to remote repo is assigned the name 'origin'.

To clone a repository from github:

git clone git@github.com:USERNAME/REPO.git

where

  • USERNAME is the github repo username
  • REPO is the name of github repo

To easily find the URL, go to the github repo and click on the green code button.

You can see the current remote repositories linked to your local git repo by typing:

git remote -v

Next to switch to a new github remote repository

git remote set-url origin git@github.com:USERNAME/REPO.git

where

  • USERNAME is the github repo username to be switched to
  • REPO is the name of github repo to be switched to

Note: url given above is based on SSH, which needs to be setup in advance. Find details on how to connect to github using SSH on their website.

Check that the details have been changed by:

git remote -v

Now force push your local repo to your github repo that you have just assigned in the above by typing:

git push -u -f origin main

And there you have it. Remember, this is a one way ticket. Once you force push your local repo, it is very difficult to go back.