Jul 03, 2016

Git Commands: Step By Step Guide (Part 2)

In this tutorial, we will go through Git commands related to Branching and Merging. Branches are used to develop features isolated from each other. It represents an independent line of development. The master branch is the "default" branch when you create a repository. Use other branches for development and merge them back to the master branch upon completion.

Before getting started, if you are beginner, I highly recommend to read the previous post which covers the basic commands:

Git Commands: Step By Step Guide (Part 1)

The following video covers to create a new branch and merge it back.

Here are the used commands in the video step by step:

1. Checkout a repository:

To create a working copy of a local repository by running the command

git clone /path/to/repository

when using a remote server, your command will be

git clone username@host:/path/to/repository

In our case, as it is public Github repo so simple link is used

2. Branching:

Let's create a new branch "branch1" and switch on it

git checkout -b branch1

Modify file2.txt manually then check status and commit it.

git status
git commit -am "Branch1 first commit"

To push the branch to your remote repository, so others can use it:

git push -u origin branch1

To list all the branches in your repository and to know what branch you're currently in, run following command:

git branch

To switch from one branch to another:

git checkout <branchname>

3. Merging:

Before merging, you can preview the changes using git diff command:

git diff master branch1

If everything looks okay then use following command to to merge branch1 into your active branch (e.g. master)

git merge branch1

4. Update your code:

To update your local repository to the newest commit from the remote repository, run following command:

git pull

5. Undo Local Changes:

If you want to sync local code with remote code and drop all your local changes and commits then run following command:

git fetch origin
git reset --hard origin/master

6. Reset Last commit only:

If you do wrong commit by mistake and want to remove all changes in last commit, run following command

git reset --hard HEAD~1

Conclusion:

In this tutorial, we have covered basic Git commands related to branching and merging.

Here is Oliver Steele's image of how all it all fits together:

Hope, It helps. Enjoy Git !!