How to Clone Into a Non-Empty Git Directory

John Wachira Feb 02, 2024
How to Clone Into a Non-Empty Git Directory

This article will teach how to clone a Git repository to a non-empty folder. This action comes in handy when you want to merge the files in your remote repository with the files in your current local repository.

Clone Into a Non-Empty Git Directory in Git

Cloning a remote repository is easy. We use the command below.

git clone <repository-url> <directory>

This will clone the remote repository to the specified directory. However, the directory should be empty.

You will get a Fatal warning message if you try to clone in a non-empty repo, as shown below.

pc@JOHN MINGW64 ~/Git (main)
$ git clone https://github.com/Wachira11ke/Delftscopetech.git
fatal: destination path 'Delftscopetech' already exists and is not an empty directory.

Since the directory Delftscopetech already exists and contains some files, we cannot use the git clone command to clone our repository.

If you don’t need the files in the directory, you can delete them, but if you want to merge the files in both repositories, use the method below.

  1. Open the directory you want to clone your remote repository into.

    cd \Delftscopetech1
    
  2. Set up a new repository with this command.

    git init
    
  3. Add the remote repository

    git remote add origin https://github.com/Wachira11ke/Delftscopetech.git
    
  4. Pull and merge

    git pull origin main --allow-unrelated-histories
    

Example:

pc@JOHN MINGW64 ~/Git (main)
$ cd \Delftscopetech1

pc@JOHN MINGW64 ~/Git/Delftscopetech1 (main)
$ git init
Initialized empty Git repository in C:/Users/pc/Git/Delftscopetech1/.git/

pc@JOHN MINGW64 ~/Git/Delftscopetech1 (master)
$ git remote add origin https://github.com/Wachira11ke/Delftscopetech.git

pc@JOHN MINGW64 ~/Git/Delftscopetech1 (master)
$ git pull origin master --allow-unrelated-histories
fatal: couldn't find remote ref master

pc@JOHN MINGW64 ~/Git/Delftscopetech1 (master)
$ git pull origin main --allow-unrelated-histories
remote: Enumerating objects: 3, done.
remote: Counting objects: 100% (3/3), done.
remote: Total 3 (delta 0), reused 0 (delta 0), pack-reused 0
Unpacking objects: 100% (3/3), 610 bytes | 3.00 KiB/s, done.
From https://github.com/Wachira11ke/Delftscopetech
 * branch            main       -> FETCH_HEAD
 * [new branch]      main       -> origin/main

We have successfully cloned our remote repo to our local repository with a non-empty directory.

Author: John Wachira
John Wachira avatar John Wachira avatar

John is a Git and PowerShell geek. He uses his expertise in the version control system to help businesses manage their source code. According to him, Shell scripting is the number one choice for automating the management of systems.

LinkedIn

Related Article - Git Clone