git: switch branch without detaching head

后端 未结 4 1642
野趣味
野趣味 2020-11-28 18:38

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

相关标签:
4条回答
  • 2020-11-28 19:19

    To expand on Kent's reply, after you do your clone the only branch you'll have (remotes don't count) is the one that was active in the repository you cloned from -- master in your case.

    So, first you'll want to create a new branch to track the remote experimental branch:

    $ git branch experimental origin/experimental
    

    and then check it out:

    $ git checkout experimental
    

    However, Kent is correct -- these two commands can be combined

    $ git checkout -b experimental origin/experimental
    
    0 讨论(0)
  • 2020-11-28 19:21
    # 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.

    0 讨论(0)
  • 2020-11-28 19:21
    git clone git@github.com:abc/def.git
    cd def
    

    Now create a tracking branch:

    git branch --track experimental origin/experimental
    git checkout experimental
    

    Then, after working there, simply push to github by

    git push
    
    0 讨论(0)
  • 2020-11-28 19:21

    With Git 2.23 (August 2019), you would use the git switch command

    If you have a remote branch of the same name, it will be automatically tracked:

    $ git switch new-topic
    Branch 'new-topic' set up to track remote branch 'new-topic' from 'origin'
    Switched to a new branch 'new-topic'
    
    0 讨论(0)
提交回复
热议问题