git checkout branch from outside

后端 未结 5 1372
我在风中等你
我在风中等你 2021-01-31 16:18

Problem: I need somehow to checkout an existing branch of a project that is already cloned locally on my file system without being in that particular folder of this project.

相关标签:
5条回答
  • 2021-01-31 16:22

    You can use --git-dir to specify the .git directory to use as the repository, and --work-tree to specify the working tree to to the checkout in. See the git man page for details.

    git --git-dir=file-system-folder/.git --work-tree=file-system-folder checkout existing-branch
    
    0 讨论(0)
  • 2021-01-31 16:22

    git 2.5 added the ability to have multiple working trees using git worktree. So this case, you'd use something like

    git worktree add -b new-branch-name ../dir-name existing-branch

    you can then change to dir-name and make your commits as usual. The commits will end up in your original repository (where you used worktree add).

    When you're done and everything you want is committed, you can delete the dir-name folder and run git worktree prune to clean up the orphaned worktree in your repo.

    0 讨论(0)
  • 2021-01-31 16:25

    You're quite welcome to use --git-dir and --work-tree to avoid cd'ing, but honestly, it's easier just to cd. To avoid having to cd back, you can do it in a subshell:

    git clone foo foo-copy
    (cd foo-copy && git checkout branch)
    

    Of course, in this specific case, you don't actually need two commands:

    git clone -b <branch-to-checkout> foo foo-copy 
    
    0 讨论(0)
  • 2021-01-31 16:27

    Since Git version 1.8.5, you can also use -C <path> option. Be sure to use it before any other command:

    git -C ~/my-git-repo checkout master

    Note that it doesn't have to be specifically the .git folder. Here is the man documenation:

    -C <path>
           Run as if git was started in <path> instead of the current 
           working directory. When multiple -C options are given, each
           subsequent non-absolute -C <path> is interpreted relative to
           the preceding -C <path>.
    
           This option affects options that expect path name like --git-dir
           and --work-tree in that their interpretations of the path names
           would be made relative to the working directory caused by the -C option.
           For example the following invocations are equivalent:
    
               git --git-dir=a.git --work-tree=b -C c status
               git --git-dir=c/a.git --work-tree=c/b status
    
    0 讨论(0)
  • 2021-01-31 16:43
    git clone ./foo ./foo-copy
    git --git-dir=./foo-copy/.git --work-tree=./foo-copy checkout branch
    
    0 讨论(0)
提交回复
热议问题