Basic Git Commands for Biginners

Version Control System GitHub Gitbash

This post is inspired by the error obtained when pushing the changes made to the Github repository which is “refusing to merge the unrelated histories”.

RPubs blog posts Twitter

Overview

As I have mentioned above from the description of this short post, I have encountered the error called refusing to merge unrelated histories, when I tried to push the changes made to my project. With this, I will discuss the possible sources, how to fix such error and how to avoid it in future project. In addition,we will also get a chance to provide the cheatsheet for basic commands in Git.

Sources of the error

Commonly, this error might be sourced from having branches with unrelated history base. This means that one is starting the branches independently of each other.For example if you start a new Git project on a local machine (i.e Rproject with Git version control) and then connect it to a remote GitHub branch (cloned from GitHub), these branches would have different history bases.

The only exception is when one of the branches has no commits in it. In this case, they should merge without a problem. Otherwise, we’ll get the refusing to merge unrelated histories like in the following example:

$ git pull origin main
#output
fatal: refusing to merge unrelated histories

How to Fix the Error

To fix the obtained error, you need to use the option –-allow-unrelated-histories after the git pull command.

Example

$ git pull origin main --allow-unrelated-histories

The –-allow-unrelated-histories option will tell the Git that we allow merging branches with no common history base, which then should finish the merge without errors.

How to avoid the Error in Future

Typically, it’s not the best practice to create a local repository branch independently of the remote repository. A more reliable way is to download the remote repository to the local machine using the git clone command.

 $ git clone <repo_url>

This way, we copy the repository from the remote server, and the commit history base remains the same for both remote and local branches.

Basic Commands in Git

Here below are some of basic commands of Git

As conclusion, the above commands are being executed in Git bash or in Terminal.