GitHub 101: Cloning and Forking

Common questions asked by people who are new to GitHub include:

Cloning and forking are two ways to make a copy of a repo, but they behave differently in terms of who can make changes and where the changes can be made.

Cloning

When you clone someone else's repo, you are making a copy of it on your computer. You can play around with the code, and even make changes to it on your own computer, but you can't push any changes back up to the repo on GitHub, because it still points to someone else's repo under their own GitHub account. When a repo exists in multiple locations besides your computer, those other locations are called remotes. To see which remotes exist, run this command:

git remote -v

When you clone a GitHub repo, it will include a remote called origin that points to the repo on GitHub. For example, if you clone the Rails repo, it will look like this:

origin  https://github.com/rails/rails.git (fetch)
origin  https://github.com/rails/rails.git (push)

Unless you have direct access to a GitHub repo (because you are the owner, or someone added you as a collaborator), you cannot push directly to it. However, you can create a new remote that points to a location that you have access to, and push your changes there. For example, you could create a new repo called rails under your own GitHub account, and then create a new remote called myrails. Then, to push the changes, you would use git push myrails instead of git push origin. But this is tedious. The easier way is to fork!

Forking

At the top right of any GitHub repo, there is a Fork button. If you hover over it, it will say Fork your own copy of [repo name] to your account. With a couple clicks, you can have a copy of a repo on your own GitHub account, which means you can push any changes to it, without affecting the original repo. Once you fork a repo, you will then want to clone it on your computer, and if you run git remote -v, you will see that the origin remote now points to your fork, which means you can push changes directly to it.

Another reason to fork is when you want to contribute to someone else's repo. For example, to fix a typo or bug, or to improve the project in some other way. Since you have direct access to your own fork, you can push the changes to it, and then you can submit a Pull Request to the original repo, which lets them know you are proposing changes, and they can decide whether or not they accept your changes, or work with you until the changes are acceptable. This is a more advanced topic that I will go into in a future guide.

For now, I wanted to give you a quick intro to the difference between forking and cloning, and when you would want to use one or the other. I've also created a visual decision tree that might help. Let me know what you think!