Search code examples
gitgithubbitbucketcloning

How can I clone a branch with the same folder name as the branch?


I tried to clone different branches in the same location but it kept creating folders having the name of the master(main) and not the specific branch.

The command I used: git clone --branch <branch-name> <git-URL>/sampleproject.git

The folder name on my local drive is sampleproject. How can I clone a branch with the folder name <branch-name>?


Solution

  • I tried to clone different branches in the same location

    I don't think you should be doing that because it introduces too many moving parts into your environment. Why not clone the repo normally and then git checkout the branch you want?

    e.g.

    cd ~/repos
    
    # Clone the repo into the directory `~/repos/sampleproject` (which will default to checking out the 'master' or 'main' branch):
    git clone <git-URL>/sampleproject.git sampleproject
    
    # Get into the repo:
    cd sampleproject
    
    # Checkout the branch 'sampleproject'
    git checkout -b sampleproject
    

    More succintly, the git clone command does let you do this in a single line:

    git clone --branch sampleproject <git-URL>/sampleproject.git sampleproject
    

    Note that the name sampleproject is repeated 3 times because:

    • --branch sampleproject is the branch that will be checkout'd.
    • sampleproject.git is the remote repo that will be cloned.
    • sampleproject (at the end) is the name of the directory in your local filesystem that the repo will be cloned into.

    But this is a bad idea: don't confuse yourself by using the same name for different things. If this were my repo I'd rename the sampleproject branch to something more descriptive.


    But rather than cloning it from a remote repo every time, why not use git's support for concurrent working-trees?

    cd ~/repos
    
    # Clone the repo into the directory `~/repos/sampleproject-master` (which will default to checking out the 'master' or 'main' branch):
    git clone <git-URL>/sampleproject.git sampleproject-master
    
    # Checkout the `branch1` branch to the directory `~/repos/sampleproject-branch1`
    git worktree add --checkout -b branch1 sampleproject-branch1
    
    # Checkout the `branch2` branch to the directory `~/repos/sampleproject-branch2`
    git worktree add --checkout -b branch2 sampleproject-branch2