How to Clone into a Non-Empty Git Directory

Cloning a git repository to a non-empty directory is useful if you have a remote repository that contains some files, and you want to merge them with the files in the local directory. Here, you will learn how to do that properly.

Steps to Cloning into a Non-empty Directory

Getting to the directory to clone

Firstly, get to the existing directory:

cd my/folder/

Setting up a repository

Create a new repository using this command:

git init

Adding to .gitignore

The next step is creating a .gitignore file and adding the files of that folder to.gitignore:

vim .gitignore

Creating a commit

When everything is ready, create the first commit using the git commit command:

git add .
git commit -m 'my first commit'

Adding to remote

Then you can add the remote from where you want to clone like this:

git remote add origin <remote-repo-url>

Pulling with local

Your final step is pulling and merging with local git:

git pull origin master --allow-unrelated-histories
In case of merge conflicts, resolve them and commit your changes.

Working with Remotes

For collaborating on a Git project, you should know how to manage remote repositories. Remote repositories are versions of your project hosted on the Internet. You can have several of them that can be either read-only or read/write for you. Working with other members of the team involves the process of pushing and pulling data to and from them. You should master the techniques of adding or removing remote repositories. You can call the git remote command to see which remote servers you have configured. It is used for creating, viewing, and removing connections to other repositories. When the repository is cloned, you should see “origin”, which is the default name that Git gives to the server you cloned from. Local copy of the central directory is an easy method of pulling upstream modifications or publishing local commits.

Fetching

The git fetch command is used for downloading commits, files, and references from a remote repository into the local repository. Both git fetch and git pull commands are designed for downloading the content from the remote repository. The git fetch command does not force to merge the changes into the repository; it just shows the progression of the central history. The fetched content does not affect the local work. It should be checked out with the git checkout command, making it safe to review commits before merging them into the local repository.