Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch to a different repository in Git

Tags:

git

github

One situation in Git that I still find confusing is this:

$ git clone https://github.com/dude1/project

Whoops, that's not really the right version. I'll switch over:

$ git remote add dude2 https://github.com/dude2/project
$ git fetch dude2
$ git checkout dude2/master

Note: checking out 'dude2/master'.

You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.

If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -b with the checkout command again. Example:

  git checkout -b new_branch_name

HEAD is now at f3o845a... 

Hrm. I want master to refer to dude2/master.

$ git checkout -b master dude2/master

fatal: A branch named 'master' already exists.

Short of deleting the whole directory and starting again, how do I cleanly switch repositories?

like image 977
Steve Bennett Avatar asked Sep 11 '25 18:09

Steve Bennett


1 Answers

In git you are not supposed to commit work on remote branches (you are supposed to do your work on local branches), that is why you are put in 'detached head' state when you checkout dude2/master. Remote branches should contain copies of commits coming from remotes, never commits created locally.

As jthill suggests, the best way to force a switch of what master means is to

git checkout -B master dude2/master

The output should include

Branch master set up to track remote branch master from dude2.

Indicating that your master is now tracking the changes of a different remote master.

like image 175
Klas Mellbourn Avatar answered Sep 13 '25 11:09

Klas Mellbourn