Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

git: switch branch without detaching head

I have a repository on github with a main branch (master) and a branch for some experimental work. I made some commits and pushed to the experimental branch and everything was fine.

Now, on a different machine, I try to clone my repository (git clone repository) and then switch to the experimental branch (git checkout branchname) but every time I do this my head gets detached and I can't push my changes. What am I doing wrong? I get the feeling I'm missing a fundamental git concept someplace but reading random git man pages isn't giving me any clues.

I'm new to git so I'm sorry if I'm being an idiot but I can't find anything in the docs that will help me reattach my head.

EDIT

The concept of a tracking branch is what I was missing. Now that I grok that concept everything is clear. Personally, I find the git branch --track syntax to be much more intuitive than git checkout -b branch-name origin/branch-name.

Thanks for the help!

like image 769
Dana Robinson Avatar asked Jan 22 '09 23:01

Dana Robinson


People also ask

How do you switch from detached head to branch?

To change from one branch to another, use git switch branchName to create a new branch, then switch to it using the git switch -c branchName command. Although finding your code in the detached HEAD state is not ideal, you can use these methods to move or remove your commits and quickly get your project back on track.


1 Answers

# first time: make origin/branchname locally available as localname git checkout -b localname origin/branchname   # othertimes  git checkout localname   git push origin 

For convenience, you may use the same string for localname & branchname
When you checked out origin/branchname you weren't really checking out a branch. origin/branchname is a "remote" name, and you can get a list of them with

branch -a  

If you have colours enabled, local branches will be one colour, and remote another.

You have to first make a remote branch tracked locally in order to be able to switch-to and work on it.

like image 176
Kent Fredric Avatar answered Oct 16 '22 10:10

Kent Fredric