Git tutorial

An essential guide to a powerful integration

Git

Project and code management together.

Try it free

Install git

First, select your PC environment:

Before we start on the tutorial, let’s get our development environment up
and running for Git. Choose your PC environment below and I will explain how we
can start setting up Git.

If you are a developer and you’re comfortable with a console interface, how
about giving the console a try for Git?

Windows

TortoiseGit is an open-source Git client.

http://code.google.com/p/tortoisegit/

To proceed with the tutorial, you will have to install msysgit on your computer. You may download the installer from http://msysgit.github.io/

First of all, download the TortoiseGit installer. Depending on your Windows OS, you will have to decide between the 32 bit or 64 bit version.

Download TortoiseGit

Start the installer by double clicking the downloaded installer file. In the next screen, click “Next”.

TortoiseGit

Click “Next” again.

Click Next again.

Select “TortoisePLink” then click “Next”.

Click Next while selecting TortoisePLink.

Click “Next” again.”

Leaving it as is, click “Next”.

Click on “Install”.

Click Install

Installation will now begin. In some cases, TortoiseGit will look for Windows user certification. If that happens, you will have to click “accept” to continue with the installation.

Installation begins

Once the installation is complete, click “Finish” to exit.

Installation is completed

Mac

On a Mac, you can use a Git client called SourceTree. It is created by
Atlassian and is free to use.

http://www.sourcetreeapp.com/

Download and double-click on the .dmg file, and drag SourceTree into the Application folder.

We are now ready to start!

GUI client called SourceTree

Command Line

Download the Git installer from the Git website at http://git-scm.com/

For Mac users, you can install Git with package management tools such as MacPorts and Homebrew.

Windows

After installation, go to Start menu > All programs > Git > Git Bash.

Mac

After installing, open Terminal which is located in Applications/Utilities.

Let’s verify that Git has been successfully installed by doing a version check. The output string may differ depending on the installed environment or the version.

$ git --version
  git version 1.7.7.5 (Apple Git-26)

Default settings

First, select your PC environment:

Now, let’s set up the default username and e-mail address for Git that will
be used to identify the person who commits the change. This setup only needs to
be done once.

Windows

From the right-click menu, click TortoiseGit > Settings.

Click TortoiseGit settings

On the settings screen, enter your name and e-mail address.

Enter the name and e-mail address as the user information on the screen of Git

Mac

Once you have successfully installed and activated SourceTree, you will be prompted by the set up wizard to enter your name and e-mail address. When you have done that, click “next”.

Enter your full name and e-mail address, and click the next button.

Next, you will be asked to fill in some information for Github and Bitbucket. We can skip that for now by just click the “next” button.

Click the following button

Click “finish” and proceed.

Click the finish button

Command Line

The Git console configuration is saved in the .gitconfig file in the
user’s home directory. You can manually edit the file but in this tutorial we
will be using the “config” command.

$ git config --global user.name ""
  $ git config --global user.email ""

Set Git output color.

$ git config --global color.ui auto

You can also set aliases for Git commands. For instance, you can
abbreviate “checkout” to “co” and use that to execute the command.

$ git config --global alias.co checkout

If you use Console (Git Bash) on Windows, a file name containing
non-ascii characters will be displayed in a form like
“\346\226\260\350\246…”. We can configure it to allow the file to display
the file name as it is by doing the following.

$ git config --global core.quotepath off

If you use Console on Windows, you can only use ascii characters.
Accordingly, if you want to include multi-byte characters in a commit
message, you have to set an external editor and should not use the -m
option.

External editors should be compatible with the character code UTF-8 and
linefeed code LF.

git config --global core.editor "\"[path of the editor you use]\"" git config --global core.editor "\"[path of the editor you use]\""

Set up is now complete! On the next page, we will start with creating a
repository.

Create a repository

First, select your PC environment:

Let’s start off by creating a new local repository. Our goal is to create a new tutorial directory and put it under the Git version control.

We will be using this directory throughout this tutorial.

Windows

Create the tutorial directory anywhere on your computer. Right-click and
then click “Git Create repository here” to have that directory tracked by
Git.

In the following screen, click “OK” without checking “Make it Bare”.

Creating repositories

Upon successfully creating a repository, click “OK” and close it in the next prompt.

Creating success screen

If everything is done correctly, the tutorial directory will now have a new
icon as shown below. If the icon remains unchanged, try right-clicking on the
file and choose “Update to the latest status”.

Tutorial Directory icon

Mac

Create the tutorial directory anywhere on your machine. After that, run
SourceTree.

Click “Add Repository” located on the top left of the bookmarks list
window. Alternatively you can choose File > New from the menu bar.

Start SourceTree

Click on “Create a Repository”. Enter the target directory name that will
be used to create a local repository. Click the “Create” button.

We will bookmark the directory as “tutorial”.

Create repository

The new repository should now be listed the bookmarks list.

Bookmark list

Command Line

Create the tutorial directory anywhere on your computer. Access the
directory and use the “init” command to turn that directory into a local Git
repository.

$ git init

Follow the steps below to turn the new tutorial directory into a Git
repository.

$ mkdir tutorial
  $ cd tutorial
  $ git init
  Initialized empty Git repository in /Users/yourname/Desktop/tutorial/.git/

Now that you’re ready, let’s commit some files to this respository.

Commit a file

First, select your PC environment:

In the tutorial directory that we have created earlier, we are going to add
a new file and have it registered under the repository.

Create a file named “sample.txt” in that directory with the following text
content.

Git commands even a monkey can understand

Windows

Open the tutorial directory and right-click on an empty space to open the right-click menu. Then, click “Git Commit” from the right-click menu.

The following screen will be displayed. Make sure the sample.txt from “Changes made” is checked. Now enter a commit message in the message box and click “OK”.

Enter a message in the "commit message" field, then click the "OK" button.

The following progress bar screen will be displayed. If it’s all good, click “Close” to finish.

If it says "Success," the attempt was successful.

Click TortoiseGit > Display Log from the right-click menu. You will find that the commit that we have just added is now listed under the history list. We have successfully commited a file!

The recent commit is added to the history.

Mac

Double click on the “tutorial” repository under the SourceTree bookmarks window. You will now see a repository operation window. If there are any newly added or edited files within the directory, they will be displayed at the bottom left of the work tree file inspector.

Because we have just added the “sample.txt” file into the “tutorial” directory, we can see it being listed there.

Repository screen

Right click on the “sample.txt” file and choose “Add to Index”. The file will now be moved to the “Files staged in the index” list above.

Click "Add to Index"

Click “Commit” in the toolbar and we will see the following screen. Enter a Commit message and click “Commit”

Enter commit message and click commit button

Once the commit is done, you will find the newly added commit being added to the “master” branch history. You can verify that the new commit is successfully added by clicking the “master” branch on the left menu.

The commit is added.

Command Line

We can use the “status” command to confirm the status of our Git working tree and index.

$ git status

Let’s execute the “status” command and inspect the status of the tutorial directory.

$ git status
  # On branch master
  #
  # Initial commit
  #
  # Untracked files:
  #   (use "git add ..." to include in what will be committed)
  #
  #     sample.txt
  nothing added to commit but untracked files present (use "git add" to track)

As we can tell from status response, “sample.txt” is currently not being tracked. You will need to add “sample.txt” to the index first in order to track its change.

In order to do that, you will use the “add” command followed by the that you wish to add to the index. If you would like to add multiple files to the index, you can do so by separating them with a space.

$ git add ..

Specify “.” instead of individual file names, if you wish to add all
of the changed files to the index.

$ git add .

Now, let’s verify that “sample.txt” has been successfully added to the index.

$ git add sample.txt
  $ git status
  # On branch master
  #
  # Initial commit
  #
  # Changes to be committed:
  #   (use "git rm --cached ..." to unstage)
  #
  #     new file:   sample.txt
  #

Now that “sample.txt” has been added to the index, we can proceed with committing the file. Use the “commit” command shown below.

$ git commit -m ""

After executing the “commit” command, check the status.

$ git commit -m "first commit"
  [master (root-commit) 116a286] first commit
    0 files changed, 0 insertions(+), 0 deletions(-)
    create mode 100644 sample.txt
  
  $ git status
  # On branch master
  nothing to commit (working directory clean)

The “status” command response tells us that there are no more new changes to be commited.

We can see the newly added commit in the repository’s history log with the “log” command.

$ git log
  commit ac56e474afbbe1eab9ebce5b3ab48ac4c73ad60e
  Author: eguchi 
  Date:   Thu Jul 12 18:00:21 2012 +0900
  
      first commit

If you prefer a GUI way of diving into the repository history, you can do so using “gitk” that is shipped along side with Git.

$ gitk
gitk

Next up, we are going to share our repository with other members in the team.

Create a remote repository

Let’s start off by creating a remote repository on Backlog.

On Backlog, only users with administrative privilege will be allowed to create new Git repositories. If you do not have administrative privilege, you will have to contact the administrator of your Space to have a new repository created. Alternatively, you can start your own Space and create a repository there. Backlog offers a free trial plan for you to get started!

Start a new space here!

First, log in to Backlog and click “Git” from the menu of the project in which you want to create a repository. If you do not have a project yet, you may want to create one first.

Click "Git" in the project in which you wish to create a repository.

If Git is not displayed as shown above, you will have to activate it by selecting the project and then go to “Project Settings” > “Git Settings”.

Enable Git function by Git configuration.

After Git feature has been activated, click “Add Repository” on the same Git Settings screen.

Click "Add a repository"

Enter the a name and description, then click the “Create Repository” button. For this tutorial, enter “tutorial” as the name and “For use in tutorial” as the description.

Click "Create Repository" button after entering "Repository name" and "Instruction".

We can see that a new repository has been added as shown below.

A new repository was added

Next, let’s push a change to this remote repository!

Push to a remote repository

First, select your PC environment:

Push the local repository “tutorial” that you have created earlier in Tutorial 1 Git Basics.

Windows

Right-click on the tutorial directory and click “Push”.

Click Push

Click “Manage” to display the next screen.

Click the control button.

In the following screen. Enter “origin” in the Remote field and enter the URL of the remote repository from the previous page and click “Add New/Save”. This will add “origin” that corresponds to the remote repository URL in the remote list. Click “OK”.

Enter the remote repository URL and click the "Add New/Save" button.

Enter the remote repository URL and click the "Add New/Save" button.

If you are on Console, the remote repository named “origin” will be used by default if you omit the remote name when pushing/pulling. That is because “origin” is commonly used as a remote name by convention.

At the Remote item on the Push screen, select “origin” which you have recently added, then click the “OK”.

Enter your Backlog username.

Enter Backlog username

Next, enter your Backlog password.

Enter Backlog password

The next screen shows that push has been successfully completed.

If you see "success" on the screen it means success.

Mac

Open SourceTree and select the “tutorial” repository.

Select "tutorial" repository

On the Repository Operations screen, click the “Settings” button on the right side of the toolbar.

Click the setting button at the right side in the tool bar on the repository operation screen.

In the next screen, click “Add”.

Click Add button

Enter “origin” in the “Remote” field and enter the URL of the remote repository from the previous page and click “OK”.

Enter the URL of the remote repository and click OK button

Enter user name and password for Backlog

Next, you will be asked to authenticate with Backlog, so enter your Backlog username and password.

Enter user name and password for Backlog

The remote repository “origin” is now shown in the Remotes list and we can start pushing changes to Backlog.

origin was added

If you are on Console, the remote repository named “origin” will be used by default if you omit the remote name when pushing/pulling. That is because “origin” is commonly used as a remote name by convention.

Now let’s try to execute a push by clicking the “push” button on the SourceTree toolbar above.

Click the push button at the tool bar on the tutorial repository operation screen.

The following dialog will be displayed. Select the “master” check box and click “OK”.

Click the OK button after check the check box of master.

When the push is successfully completed, “origin/master” which represents the commit on remote will be shown in the Description column of the commit.

The "origin/master" shown by the remote repository has been added.

Command Line

You can give an alias or nickname to a remote repository. This is helpful as we do not need to remember the long address of the remote repository each time we intend to do a push. In this tutorial, we will register a remote repository name as “origin”.

To add a remote repository, use the “remote” command. is used as an alias of a remote repository, followed by with the URL of the remote repository.

$ git remote add

Execute the command using the URL of the remote repository from the previous page. The new remote repository URL will be given an alias of “origin”.

The remote repository‘s URL is registered under the name "origin".
$ git remote add origin https://[your_space_id].backlogtool.com/git/[your_project_key]/tutorial.git

The remote repository named “origin” will be used by default if you omit the remote name when pushing/pulling. That is because “origin” is commonly used as a remote name by convention.

To push changes to the remote repository, use the “push” command. Assign the address in , and the branch name in , that you wish to push to. We will be covering branch in greater depth in the “Working with Git” section.

$ git push  ...

Run the following command to push a commit to the remote repository “origin”. If you specify the -u option when executing the command, you can omit the branch name the next time you push to the remote repository. When you push to a vacant remote however, you must specify the remote repository and branch name.

When asked for the user name and password, enter your Backlog user credentials.

$ git push -u origin master
  Username: 
  Password: 
  Counting objects: 3, done.
  Writing objects: 100% (3/3), 245 bytes, done.
  Total 3 (delta 0), reused 0 (delta 0)
  To https://monkey.backlogtool.com/git/BLGGIT/tutorial.git
    * [new branch]      master -> master

Open the Git page on Backlog. You will find that a new update that corresponds to your push to the remote repository has been listed under recent updates.

The push item is added to the recent updates.

The pushed file has also been added under the list of files of the remote repository.

The file from the pushed repository is added.

Next, let’s clone this remote repository!

Clone a remote repository

First, select your PC environment:

Make a copy of a remote repository so that you can start work on it on your local machine.

Now, let’s assume the role of another member in the team and clone the existing remote repository onto another directory named “tutorial 2”.

Windows

Double-click anywhere on the desktop and click “Git Clone” in the right-click menu.

Click Git Clone

Enter the remote repository URL that we want to clone and the name of the directory to be saved. Click “OK”.

In this example, we are cloning the remote repository that was created in the previous page but with a different directory name (“tutorial 2”).

Cloning will begin in the next screen. When that is completed, click “Close” to finish.

Clone succeeded

The directory “tutorial 2” has now been created.

Directory tutorial2 was created

To verify that the cloning has been executed successfully, check that the following line is contained within sample.txt of the newly cloned directory “tutorial 2”.

Git commands even a monkey can understand

Mac

In the upper left corner of the SourceTree bookmarks window, click “Add Repository”. Alternatively, you can also select “File” > “New/Clone” from the menu bar.

Start SourceTree

Select the “Clone Repository” above. Now enter the remote repository URL and the name of the new directory to be saved. Click “Create”.

In this example, we are cloning the remote repository that was created in the previous page but with a different directory name (“tutorial 2”).

Clone into the directory named "tutorial2".

The newly cloned repository is now added to the bookmarks list.

Added to the bookmark list.

To verify that the cloning has been executed successfully, check that the following line is contained within sample.txt of the newly cloned “tutorial 2” directory.

Git commands even a monkey can understand

Command Line

Use the “clone” command to copy a remote repository as shown in the example below. Substitute with the remote repository URL and with the new directory name in which the remote contents will be placed.

$ git clone

By executing the following command, the remote repository will be copied into the directory named tutorial2.

$ git clone https://monkey.backlogtool.com/git/BLGGIT/tutorial.git tutorial2
  Cloning into 'tutorial2'...
  Username:
  Password:
  remote: Counting objects: 3, done.
  remote: Total 3 (delta 0), reused 0 (delta 0)
  Unpacking objects: 100% (3/3), done.

To verify that the cloning has been executed successfully, check that the following line is contained within sample.txt of the newly cloned “tutorial 2” directory.

Git commands even a monkey can understand

Push from a cloned repository

First, select your PC environment:

Let’s try pushing from the previously cloned repository.

Windows

First, lets add the bold text below to “sample.txt” in the newly cloned directory and commit the change.

Git commands even a monkey can understand
  add: Register a change in an index

We can see that the history log of our local repository branch has been updated and is now ahead of the remote repository branch.

The local repository‘s commit has advanced.

Next, let’s push this new commit to the remote repository. Right-click on the directory “tutorial2″and click “Push”.

Right-click "tutorial2" directory and click Push button.

Click “OK” to proceed to the next screen.

Click OK button

Working in tutorial2

The following screen shows that “Push” is in progress. Once it is complete, click “Close” to finish.

The next screen will be shown and the Push will begin.

Select TortoiseGit > Display log from the right-click menu. Now “master” and “origin/master” are both on the same level. What that means is that the remote repository is now up to date with the latest change and is now in-sync with our local repository.

Origin/master‘s commit has progressed.

Let’s review the location that each of the following references point.

  • origin/masterPoints to the master branch of “origin” which is typically the remote repository.
  • origin/HEAD
    Refers to the current commit of “origin” which is the remote repository. In most cases, the local repository would always point to the same location as origin/HEAD when performing a clone, which is also the equivalent of origin/master. This won’t be the case, however, if you check out to a different remote branch.
  • master
    Points to the master branch of the local repository.

We will cover branch in greater detail in the “Working with Git” section.

Mac

First, lets add the bold text below to “sample.txt” in the newly cloned directory and commit the change.

Git commands even a monkey can understand
  add: Register a change in an index

We can see that the history log of our local repository branch has been updated and is now ahead of the remote repository branch.

The local repository‘s commit has advanced.

Next, let’s push this new commit to the remote repository. Click “Push” in the toolbar.

Click Push in the toolbar

Make sure the master checkbox is checked and proceed by clicking “OK”.

Confirm that the "master" checkbox is selected, then click the "OK" button.

Now “master” and “origin/master” are both on the same level. What that means is that the remote repository is now up to date with the latest change and is now in-sync with our local repository.

Origin/master‘s commit has progressed.

Let’s review the location that each of the following references points.

  • origin/master
    Points to the “master” branch of “origin” which is typically the remote repository.
  • origin/HEAD
    Refers to the current commit of “origin” which is the remote repository. When doing a clone, in most cases, the local repository would always point to the same location as origin/HEAD; that is also the equivalent of origin/master. This won’t be the case however, if you checkout to a different remote branch.
  • master
    Points to the “master” branch of our local repository.

We will cover branch in greater detail in the “Working with Git” section.

Command Line

First, lets add the bold text below to “sample.txt” in the newly cloned directory and commit the change.

Git commands even a monkey can understand
  add: Register a change in an index
$ git add sample.txt
  $ git commit -m "append description of the add command"
  [master 1ef5c8c] append description of the add command
  1 files changed, 1 insertions(+), 1 deletions(-)

Next, let’s push this new commit to the remote repository

You can omit the repository and branch name when executing “push” in a cloned repository directory.

$ git push
  Username: <username>
  Password: <password>
  Counting objects: 5, done.
  Delta compression using up to 4 threads.
  Compressing objects: 100% (2/2), done.
  Writing objects: 100% (3/3), 351 bytes, done.
  Total 3 (delta 0), reused 0 (delta 0)
  To https://monkey.backlogtool.com/git/BLGGIT/tutorial.git
      486789c..1ef5c8c  master -> master

You will now find the newly pushed commit on Backlog. It will be listed under “recent updates” on Backlog’s Git page.

The commit you have just pushed has been added to the lastest update.

Pull from a repository

First, select your PC environment:

In this section, we are going to pull the latest change from the remote repository to our local repository (tutorial directory).

Windows

Now that our remote repository is up to date with the changes from “tutorial2”, let’s pull the change and synchronize our initial repository directory, “tutorial”.

To execute a “pull”, right-click on the tutorial directory and select pull from the right-click menu.

Click pull from the right-click menu

Click “OK”.

Click OK button

Pull will be in progress. Once complete, click “Close” to finish.

When the next screen is displayed, the pull will begin.

Click TortoiseGit > Diplay Log from the right-click menu. You will now notice that master has moved forward to the same level as origin/master. This means that our tutorial local repository is now up to date with the latest changes from the remote repository.

The origin/master have advanced to the same position.

Mac

Now that our remote repository is up to date with the changes from “tutorial2”, let’s pull the change and synchronize our initial repository directory, “tutorial”.

To execute a “pull”, click “Pull” on the toolbar.

Click Pull button on the toolbar

In the next screen, you do not have to change anything, just proceed with clicking “OK”.

Click OK button

You will now notice that master has moved forward to the same level as origin/master. This means that our tutorial local repository is now up to date with the latest changes from the remote repository.

The origin/master have advanced to the same position.

Command Line

Now that our remote repository is up to date with the changes from “tutorial2”, let’s pull the change and synchronize our initial repository directory, “tutorial”.

To execute a pull, use the “pull” command. If you do not include the repository name, the pull will be executed on the repository under the alias of “origin”.

$ git pull  ...

Execute the following command.

$ git pull origin master
  Username: 
  Password: 
  From https://monkey.backlogtool.com/git/BLGGIT/tutorial.git
  * branch            master     -> FETCH_HEAD
  Updating ac56e47..3da09c1
  Fast-forward
  sample.txt |    1 +
    1 files changed, 1 insertions(+), 0 deletions(-)

Let’s verify that the history is updated with the “log” command.

$ git log
  commit 3da09c1134a41f2bee854a413916e4ebcae7318d
  Author: eguchi 
  Date:   Thu Jul 12 18:02:45 2012 +0900
  
  append description of the add command
  
  commit ac56e474afbbe1eab9ebce5b3ab48ac4c73ad60e
  Author: eguchi 
  Date:   Thu Jul 12 18:00:21 2012 +0900
  
      first commit

Looks good, the new commit that we have added in “tutorial2” is now listed under this repository’s history log.

Let’s open the file sample.txt and check the content.

Git commands even a monkey can understand
  add: Register a change in an index

We should see the newly added content “add: Register a change in an index”

Make a conflict

First, select your PC environment:

In this tutorial, we are going to learn how to resolve a conflict. In order to do that, we are going to start off by deliberately creating a conflict using our two existing repositories, “tutorial” and “tutorial 2”.

Windows

First, open the “sample.txt” file in the “tutorial” directory. Add the bold text below to the file and commit.

Git commands even a monkey can understand
  add: Register a change in an index
  commit: Save the status of an index
Record the status of commit index

Next, open the “sample.txt” file in the “tutorial2” directory. Add the bold text below to the file and commit.

Git commands even a monkey can understand
  add: Register a change in an index
  pull: Obtain the content of the remote repository
"pull" Acquire the contents of a remote repository.

Now push the change from “tutorial2” to the remote repository.

Push to the remote repository

In our current remote repository, the “sample.txt” file contains the third line “pull: Obtain the content of the remote repository” and has been commited in the history log.

Now, we are going to push the commit from our “tutorial” repository to the remote repository.

Push to the remote repository

Mac

First, open the “sample.txt” file in the “tutorial” directory. Add the bold text below to the file and commit.

Git commands even a monkey can understand
  add: Register a change in an index
  commit: Save the status of an index
Record the status of commit index

Next, open the “sample.txt” file in the “tutorial2” directory. Add the bold text below to the file and commit.

Git commands even a monkey can understand
  add: Register a change in an index
  pull: Obtain the content of the remote repository
"pull" Acquire the contents of a remote repository.

Now push the change from “tutorial2” to the remote repository.

In our current remote repository, the “sample.txt” file contains the third line “pull: Obtain the content of the remote repository” and has been commited in the history log.

Now, we are going to push the commit from our “tutorial” repository to the remote repository.

Push to the remote repository

Command Line

First, open the “sample.txt” file in the “tutorial” directory. Add the bold text below to the file and commit.

Git commands even a monkey can understand
  add: Register a change in an index
  commit: Save the status of an index
$ git add sample.txt
  $ git commit -m "append description of the commit command"
  [master 95f15c9] append description of the commit command
    1 files changed, 1 insertions(+), 0 deletions(-)

Next, open the “sample.txt” file in the “tutorial2” directory. Add the bold text below to the file and commit.

Git commands even a monkey can understand
  add: Register a change in an index
  pull: Obtain the content of the remote repository
$ git add sample.txt
  $ git commit -m "append description of the pull command"
  [master 4c01823] append description of the pull command
    1 files changed, 1 insertions(+), 0 deletions(-)

Now push the change from “tutorial2” to the remote repository.

$ git push
  Username: <username>
  Password: <password>
  Counting objects: 5, done.
  Delta compression using up to 4 threads.
  Compressing objects: 100% (2/2), done.
  Writing objects: 100% (3/3), 391 bytes, done.
  Total 3 (delta 0), reused 0 (delta 0)
  To https://monkey.backlogtool.com/git/BLGGIT/tutorial.git
      3da09c1..4c01823  master -> master

In our current remote repository, the “sample.txt” file contains the third line “pull: Obtain the content of the remote repository” and has been commited in the history log.

Now, we are going to push the commit from our “tutorial” repository to the remote repository.

$ git push
  Username: <username>
  Password: <password>
  To https://monkey.backlogtool.com/git/BLGGIT/tutorial.git
  ! [rejected]        master -> master (non-fast-forward)
  error: failed to push some refs to 'https://monkey.backlogtool.com/git/BLGGIT/tutorial.git'
  To prevent you from losing history, non-fast-forward updates were rejected
  Merge the remote changes (e.g. 'git pull') before pushing again.  See the
  'Note about fast-forwards' section of 'git push --help' for details.

As you can see, Git will raise a conflict and reject your push.

Resolve a conflict

First, select your PC environment:

In order to proceed with pushing the change to the remote repository, we will have to manually resolve the conflict. Let’s execute a pull to acquire the most recent change set from the remote repository.

Windows

Execute a pull by right-clicking on the “tutorial” directory and click pull.

Click Pull from right-click menu.

Click “OK” in the following screen.

Click OK button

We will now see a warning message saying that the automatic merge has failed. Click “Close”.

The message "automatic merge failed" comes up

You will be prompted on whether you would like to see the changes in this revision. Click “Yes”.

Click Yes button

TortoiseGit is telling us that the automatic merge has failed because “sample.txt” has a merge conflict. Click “OK”.

The conflicts have happened.

When you open “sample.txt”, you can see markers that have been added by Git to indicate conflicts in that section of the file as shown below.

Git commands even a monkey can understand
  add: Register a change in an index
  <<<<<<< HEAD
  commit: Save the status of an index
  =======
  pull: Obtain the content of the remote repository
  >>>>>>> 17c860612953c0f9d88f313c8dfbf7d858e02e91

We are going to resolve the conflict by accepting both changes and remove the marker.

Git commands even a monkey can understand
  add: Register a change in an index
  commit: Save the status of an index
  pull: Obtain the content of the remote repository

Now that we have resolved the conflict and the content of the file has changed, we will need to initiate a commit. Right click and choose “Commit”.

We are now up to date with the latest change from the remote repository.

Completed acquiring the latest changes from the remote repository.

Mac

Execute a pull by clicking “Pull” on the toolbar menu.

Execute pull

Click “OK” in the next screen to proceed.

Click OK button

A dialog will pop up warning us of a merge conflict.

Conflict occurred during the merge.

When you open “sample.txt”, you can see markers that have been added by Git to indicate conflicts in that section of the file as shown below.

Git commands even a monkey can understand
  add: Register a change in an index
  <<<<<<< HEAD
  commit: Save the status of an index
  =======
  pull: Obtain the content of the remote repository
  >>>>>>> 17c860612953c0f9d88f313c8dfbf7d858e02e91

We are going to resolve the conflict by accepting both changes and remove the marker.

Git commands even a monkey can understand
  add: Register a change in an index
  commit: Save the status of an index
  pull: Obtain the content of the remote repository

Now that we have resolved the conflict and the content of the file has changed, we will need to initiate a commit. Right click and choose “Commit”.

We are now up to date with the latest change from the remote repository.

Completed acquiring the latest changes from the remote repository.

Command Line

Execute the following command

$ git pull origin master
  Username: 
  Password: 
  remote: Counting objects: 5, done.
  remote: Compressing objects: 100% (2/2), done.
  remote: Total 3 (delta 0), reused 0 (delta 0)
  Unpacking objects: 100% (3/3), done.
  From https://monkey.backlogtool.com/git/BLGGIT/tutorial.git
  * branch            master     -> FETCH_HEAD
  Auto-merging sample.txt
  CONFLICT (content): Merge conflict in sample.txt
  Automatic merge failed; fix conflicts and then commit the result.

A message should appear warning us of a merge conflict.

When you open “sample.txt”, you can see markers that have been added by Git to indicate conflicts in that section of the file as shown below.

Git commands even a monkey can understand
  add: Register a change in an index
  <<<<<<< HEAD
  commit: Save the status of an index
  =======
  pull: Obtain the content of the remote repository
  >>>>>>> 17c860612953c0f9d88f313c8dfbf7d858e02e91

We are going to resolve the conflict by accepting both changes and remove the marker.

Git commands even a monkey can understand
  add: Register a change in an index
  commit: Save the status of an index
  pull: Obtain the content of the remote repository

When you are done editing the file, you will need to commit.

$ git add sample.txt
  $ git commit -m "merge"
  [master d845b81] merge

We are now up to date with the latest change from the remote repository.

We can verify the accuracy of the repository history using the “log” command. The –graph option will show the branch history in a graph format and the –oneline will try to compact the output message.

$ git log --graph --oneline
  *   d845b81 merge
  |\
  | * 4c01823 append description of the pull command
  * | 95f15c9 append description of the commit command
  |/
  * 3da09c1 append description of the add command
  * ac56e47 first commit

This indicates that the two histories have been merged successfully with a new merge commit.

We can safely push this change to the remote repository without any merge conflicts.

Create a branch

Create a new directory and initialize a Git repository. We are going to create a directory named “tutorial”.

$ mkdir tutorial
  $ cd tutorial
  $ git init
  Initialized empty Git repository in /Users/eguchi/Desktop/tutorial/.git/

Create a new file named “myfile.txt” in the tutorial directory and commit.

Git commands even a monkey can understand
  $ git add myfile.txt
  $ git commit -m "first commit"
  [master (root-commit) a73ae49] first commit
  1 files changed, 1 insertions(+), 0 deletions(-)
    create mode 100644 myfile.txt

At this point, the history tree should look like this.

Current history

Let’s create a new branch with the name “issue1”.

Use the branch command with a name to create a new branch with that name.

$ git branch

Create a new branch named issue1.

$ git branch issue1

If you do not specify any parameters, the branch command will list all branches that correspond to this repository. The asterisk indicates the current active branch.

$ git branch
      issue1
      * master

At this point, the history tree should look like this.

Current history

Switch branches

Switch over to the branch “issue1” when you want to add new commits to it.

Use the checkout command to switch branch.

$ git checkout

Switch to the branch “issue1” by doing the following.

$ git checkout issue1
  Switched to branch 'issue1'

This history tree should look like this at the moment.

Current history

By passing in the -b option when executing the checkout command, a new branch will be created and you will be switched over thereafter.

$ git checkout -b

Once you are on the “issue1” branch, you can start adding commits to it. Let’s add the bold text below to myfile.txt and commit the change.

Git commands even a monkey can understand
  add: Register a change in an index
$ git add myfile.txt
  $ git commit -m "append description of the add command"
  [issue1 b2b23c4] append description of the add command
   1 files changed, 1 insertions(+), 0 deletions(-)

Our history tree will now look like this.

Current history

Merge branches

Let’s merge “issue1” with “master”

Current history

Use the merge command to merge branches.

$ git merge

By running the command above, the specified commit will be merged to the current active branch. Most of the time, you will want to merge a branch with the current active branch and you can do so by passing in the branch name in .

To merge commits into the master branch, let’s now switch over to the master branch.

$ git checkout master
  Switched to branch 'master'

Before merging, open myfile.txt and check the content of the file.

Git commands even a monkey can understand

As shown above, the change added on “issue1” described in the previous page isn’t included in myfile.txt on master branch.

$ git merge issue1
  Updating 1257027..b2b23c4
  Fast-forward
  myfile.txt |    1 +
  1 files changed, 1 insertions(+), 0 deletions(-)

The position of the master branch will now move over to that of “issue1”. A fast-forward merge has been executed here.

Current history

Now, let’s confirm myfile.txt.

Git commands even a monkey can understand
  add: Register a change in an index

Open myfile.txt and you will notice that the new line that we have committed to the “issue1” branch is now here on the master branch.

Delete branches

Now that “issue1” has been successfully merged with “master”, we can delete it.

We can delete a branch by calling the branch command and passing in the -d option, followed by the branch name.

$ git branch -d

Run the following command to delete “issue1”.

$ git branch -d issue1
  Deleted branch issue1 (was b2b23c4).

We can verify that “issue1” has been deleted by calling “git branch”. Only the master branch should be listed.

$ git branch
  * master
Current history

Work in parallel

Branching allows us to work in multiple parallel workspaces.

Let’s create two branches. Create one with the name “issue2″ and another with the name”issue3”, then switch over to “issue2”.

$ git branch issue2
  $ git branch issue3
  $ git checkout issue2
  Switched to branch 'issue2'
  $ git branch
  * issue2
    issue3
    master
Current history

Add the bold text below to myfile.txt and commit the change.

Git commands even a monkey can understand
  add: Register a change in an index
  commit: Save the status of an index
$ git add myfile.txt
  $ git commit -m "append description of the commit command"
  [issue2 8f7aa27] append description of the commit command
    1 files changed, 2 insertions(+), 0 deletions(-)
Current history

Now switch to “issue3” branch.

$ git checkout issue3
  Switched to branch 'issue3'

“issue3” currently has the same history/content as the master branch. It will not include the recent change that we have just made. This is because the recent change has been commited to the “issue2” branch.

Add the bold text below to myfile.txt and commit the change.

Git commands even a monkey can understand
  add: Register a change in an index
  pull: Obtain the content of the remote repository
$ git add myfile.txt
  $ git commit -m "append description of the pull command"
  [issue3 e5f91ac] append description of the pull command
    1 files changed, 2 insertions(+), 0 deletions(-)
Current history

We have now added two different line of texts to two different branches in parallel.

Resolve a merge conflict

Now let’s merge branches “issue2” and “issue3” into the master branch.

We will switch over to “master” and merge “issue2” with it.

$ git checkout master
  Switched to branch 'master'
  $ git merge issue2
  Updating b2b23c4..8f7aa27
  Fast-forward
  myfile.txt |    2 ++
    1 files changed, 2 insertions(+), 0 deletions(-)

A fast-forward merge has now been executed.

Current history

Let’s try to merge “issue3” into “master”.

$ git merge issue3
  Auto-merging myfile.txt
  CONFLICT (content): Merge conflict in myfile.txt
  Automatic merge failed; fix conflicts and then commit the result.

Git has identified a conflict and will not allow you to automatically merge “issue3” with “master”. The conflict here pertains to the same line on myfile.txt with different content on both branches. Due to the conflict during the attempt to merge, myfile.txt will look something like this.

Git commands even a monkey can understand
  add: Register a change in an index
  <<<<<<< HEAD
  commit: Save the status of an index
  =======
  pull: Obtain the content of a remote repository
  >>>>>>> issue3

You will find some strange markers being added to myfile.txt. These markers were added by Git, giving us information regarding which line of the file is related to the conflict. We will have to manually fix the conflict as shown below.

Git commands even a monkey can understand
  add: Register a change in an index
  commit: Save the status of an index
  pull: Obtain the content of a remote repository

Once we are done with resolving the conflict, let’s commit the change.

$ git add myfile.txt
  $ git commit -m "merge issue3 branch"
  # On branch master
  nothing to commit (working directory clean)

The revision history will now look like the one below. A new merge commit has been created as a result of the conflict resolution. The master branch is now pointing to the latest merge commit. This is a non fast-forward merge.

Current history

Rebase a branch

Another approach we can take to integrate “issue3” branch into the master branch is by using the rebase command. Using rebase, we can streamline and clean our history tree just like how we have described earlier.

Let’s start by undoing the previous merge.

$ git reset --hard HEAD~
History before rebase

Switch over to “issue3” branch and rebase onto the master branch.

$ git checkout issue3
  Switched to branch 'issue3'
  $ git rebase master
  First, rewinding head to replay your work on top of it...
  Applying: append description of the pull command
  Using index info to reconstruct a base tree...
  :13: new blank line at EOF.
  +
  warning: 1 line adds whitespace errors.
  Falling back to patching base and 3-way merge...
  Auto-merging myfile.txt
  CONFLICT (content): Merge conflict in myfile.txt
  Failed to merge in the changes.
  Patch failed at 0001 append description of the pull command
  
  When you have resolved this problem run "git rebase --continue".
  If you would prefer to skip this patch, instead run "git rebase --skip".
  To check out the original branch and stop rebasing run "git rebase --abort".

When a conflict occurs during the rebase, you will have to resolve it immediately in order to resume the rebase operation.

Git commands even a monkey can understand
  add: Register a change in an index
  <<<<<<< HEAD
  commit: Save the status of an index
  =======
  pull: Obtain the content of a remote repository
  >>>>>>> issue3

Once the conflict is resolved, you can resume rebase with the –continue option. If you wish to quit and rollback the rebase operation, you can do so by passing in the –abort option.

$ git add myfile.txt
  $ git rebase --continue
  Applying: append description of the pull command
Current history

With the “issue3” branch rebased onto “master”, we can now issue a fast-forward merge.

Switch over to the master branch and merge “issue3” with “master”.

$ git checkout master
  Switched to branch 'master'
  $ git merge issue3
  Updating 8f7aa27..96a0ff0
  Fast-forward
  myfile.txt |    1 +
    1 files changed, 1 insertions(+), 0 deletions(-)

The content of myfile.txt should now be identical to the one that we got from the previous merge. The revision history now should look like the following.

Current history

Add a tag

Preliminary preparation

Let’s create a new directory and initialize a new empty repository. For this example, we will create a directory with the name “tutorial”.

$ mkdir tutorial
  $ cd tutorial
  $ git init
  Initialized empty Git repository in /Users/eguchi/Desktop/tutorial/.git/

Create a file with the name myfile.txt in the tutorial directory. Put in the text content below and commit it.

Git commands even a monkey can understand
  $ git add myfile.txt
  $ git commit -m "first commit"
  [master (root-commit) a73ae49] first commit
  1 files changed, 1 insertions(+), 0 deletions(-)
    create mode 100644 myfile.txt

At this point, the revision history should look like this.

Current history

Add a lightweight tag

Use the tag command to add a new tag. Enter a tag name in <tagname>.

$ git tag <tagname>

Run the following command to add a tag named “apple” to HEAD.

$ git tag apple

Running tag without any parameters gives you a list of tags in this repository.

$ git tag
  apple

To see the history log with tag information, executing “log” with the –decorate option.

$ git log --decorate
  commit e7978c94d2104e3e0e6e4a5b4a8467b1d2a2ba19 (HEAD, tag: apple, master)
  Author: yourname <yourname@yourmail.com>
  Date:   Wed Jul 18 16:43:27 2012 +0900
  
      first commit
Add a tag "apple" to the commit indicated by the current HEAD.

Add an annotated tag

We can add an annotated tag by running “tag” with the -a option, which opens the default text editor that lets you add notes to the tag.

You can also pass the -am option instead if you want to add the note alongside the tag creation.

$ git tag -a <tagname>

Run the following command to add a tag for HEAD named “banana” with some notes.

$ git tag -am "Git Beginner's Guide" banana

Passing in the -n option gives you the list of tags with their notes for this repository.

$ git tag -n
  apple           first commit
  banana          Git Beginner's Guide
Add a tag with an annotation "banana" to a commit which HEAD is pointing out now.

Delete a tag

To delete a tag, run “tag” with -d option and enter the name of the tag you wish to delete in <tagname>.

$ git tag -d <tagname>
Delete a tag

Commit –amend

For this tutorial step, we have prepared a repository with some ready made commits to speed things up.

You can download the repository here.

Let’s rewrite the first commit in the history log.

Go to the downloaded “stepup-tutorial/tutorial1” directory. Take some time to examine the history of this repository. It should look like the following.

The history of repository.

You can examine the repository’s history using the log command.

$ git log
  commit 326fc9f70d022afdd31b0072dbbae003783d77ed
  Author: yourname <yourname@yourmail.com>
  Date:   Mon Jul 16 23:17:56 2012 +0900
  
      append description of the add command
  
  commit 48eec1ddf73a7fb508ef664efd6b3d873631742f
  Author: yourname <yourname@yourmail.com>
  Date:   Mon Jul 16 23:16:14 2012 +0900
  
      first commit

Open the sample.txt files and add the bold text below.

Git commands even a monkey can understand
  add: Register a change in an index
  commit: Save the status of an index

Commit with the –amend option.

$ git add sample.txt
  $ git commit --amend

Your default editor should open containing the latest commit message which you can edit. For this tutorial, let’s change the message to “Add direction of the Add and the Commit”, then save and exit the text editor.

The commit message should now be updated. Use the log command to verify the repository history and the new commit message.

commit --amend
$ git log
  commit e9d75a02e62814541ee0410d9c1d1bf47ab1c057
  Author: yourname 
  Date:   Mon Jul 16 23:17:56 2012 +0900
  
      Add direction of the Add and the Commit.
  
  commit 48eec1ddf73a7fb508ef664efd6b3d873631742f
  Author: yourname 
  Date:   Mon Jul 16 23:16:14 2012 +0900
  
      first commit

Revert

For this tutorial step, we have prepared a repository with some ready made commits to speed things up.

You can download the repository here.

We are going to undo the “append description of the pull command” commit using the “revert” command.

Go to the downloaded “stepup-tutorial/tutorial2” directory and examine the history of this repository. It should look like the following.

Current history

Examine the history log using the log command.

$ git log
  commit 0d4a808c26908cd5fe4b6294a00150342d1a58be
  Author: yourname <yourname@yourmail.com>
  Date:   Mon Jul 16 23:19:26 2012 +0900
  
      append description of the pull command
  
  commit 9a54fd4dd22dbe22dd966581bc78e83f16cee1d7
  Author: yourname <yourname@yourmail.com>
  Date:   Mon Jul 16 23:19:01 2012 +0900
  
      append description of the commit command
  
  commit 326fc9f70d022afdd31b0072dbbae003783d77ed
  Author: yourname <yourname@yourmail.com>
  Date:   Mon Jul 16 23:17:56 2012 +0900
  
      append description of the add command
  
  commit 48eec1ddf73a7fb508ef664efd6b3d873631742f
  Author: yourname <yourname@yourmail.com>
  Date:   Mon Jul 16 23:16:14 2012 +0900
  
      first commit

Open the sample.txt file and verify its content.

Git commands even a monkey can understand
  add: Register a change in an index
  commit: Save the status of an index
  pull: Obtain the content of the remote repository

Let’s undo the latest HEAD commit titled “append description of the pull command” using the revert command.

$ git revert HEAD
  [master d47bb1d] Revert "append description of the pull command"
    1 files changed, 1 insertions(+), 2 deletions(-)

Open sample.txt. If the above procedure has been done correctly, the last line “pull: Obtain the content of the remote repository” should no longer exist.

The history of repository after the revert.

You can confirm the new history log using the “log” command.

$ git log
  commit 7bcf5e3b6fc47e875ec226ce2b13a53df73cf626
  Author: yourname <yourname@yourmail.com>
  Date:   Wed Jul 18 15:46:28 2012 +0900
  
      Revert "append description of the pull command"
  
      This reverts commit 0d4a808c26908cd5fe4b6294a00150342d1a58be.
  
  commit 0d4a808c26908cd5fe4b6294a00150342d1a58be
  Author: yourname <yourname@yourmail.com>
  Date:   Mon Jul 16 23:19:26 2012 +0900
  
      append description of the pull command
  
  commit 9a54fd4dd22dbe22dd966581bc78e83f16cee1d7
  Author: yourname <yourname@yourmail.com>
  Date:   Mon Jul 16 23:19:01 2012 +0900
  
      append description of the commit command
  
  commit 326fc9f70d022afdd31b0072dbbae003783d77ed
  Author: yourname <yourname@yourmail.com>
  Date:   Mon Jul 16 23:17:56 2012 +0900
  
      append description of the add command
  
  commit 48eec1ddf73a7fb508ef664efd6b3d873631742f
  Author: yourname <yourname@yourmail.com>
  Date:   Mon Jul 16 23:16:14 2012 +0900
  
      first commit

Reset

For this tutorial step, we have prepared a repository with some ready made commits to speed things up.

You can download the repository here.

In this step, we are going to undo the previous two commits using the reset command.

Go to the downloaded “stepup-tutorial/tutorial3” directory and examine the history of this repository. It should look like the following.

Current history

Let’s confirm the branch’s history using the log command.

$ git log
  commit 0d4a808c26908cd5fe4b6294a00150342d1a58be
  Author: yourname <yourname@yourmail.com>
  Date:   Mon Jul 16 23:19:26 2012 +0900
  
      append description of the pull command
  
  commit 9a54fd4dd22dbe22dd966581bc78e83f16cee1d7
  Author: yourname <yourname@yourmail.com>
  Date:   Mon Jul 16 23:19:01 2012 +0900
  
      append description of the commit command
  
  commit 326fc9f70d022afdd31b0072dbbae003783d77ed
  Author: yourname <yourname@yourmail.com>
  Date:   Mon Jul 16 23:17:56 2012 +0900
  
      append description of the add command
  
  commit 48eec1ddf73a7fb508ef664efd6b3d873631742f
  Author: yourname <yourname@yourmail.com>
  Date:   Mon Jul 16 23:16:14 2012 +0900
  
      first commit

Open sample.txt and verify that the text content looks something like below.

Git commands even a monkey can understand
  add: Register a change in an index
  commit: Save the status of an index
  pull: Obtain the content of the remote repository

Use the reset command to delete the previous two commits like below.

Delete the commit
$ git reset --hard HEAD~~
  HEAD is now at 326fc9f append description of the add command

If done correctly, sample.txt should no longer contain the last two lines “commit: Save the status of an index” and “pull: Obtain the content of the remote repository”. You can also verify that these commits are no longer in the history with the log command.

$ git log
  commit 326fc9f70d022afdd31b0072dbbae003783d77ed
  Author: yourname <yourname@yourmail.com>
  Date:   Mon Jul 16 23:17:56 2012 +0900
  
      append description of the add command
  
  commit 48eec1ddf73a7fb508ef664efd6b3d873631742f
  Author: yourname <yourname@yourmail.com>
  Date:   Mon Jul 16 23:16:14 2012 +0900
  
      first commit

ORIG_HEAD points to the original commit before reset actually takes place. This may come in handy especially when you accidentally issue a reset. You can restore the previous history by executing a reset to ORIG_HEAD.

$ git reset --hard ORIG_HEAD
  HEAD is now at 0d4a808 append description of the pull command

Cherry pick

For this tutorial step, we have prepared a repository with some ready made commits to speed things up.

You can download the repository here.

Go to the downloaded “stepup-tutorial/tutorial4” directory and examine the history of this repository. It should look like the following.

In this step, we are going to create a new commit in the master branch that is a copy of the commit with the message “append description of the commit command” residing on a different branch within the same repository.

Current history

Switch over to the master branch. Use the cherry-pick command and specify the commit hash for “append description of the commit command”.

The commit hash “99daed2” may differ on your local repository. You can obtain the commit hash by running “git log” in that branch. Find out the commit hash on your local repository and use that instead.

$ git checkout master
  Switched to branch 'master'
  $ git cherry-pick 99daed2
  error: could not apply 99daed2... commit
  hint: after resolving the conflicts, mark the corrected paths
  hint: with 'git add <paths>' or 'git rm <paths>'
  hint: and commit the result with 'git commit'

As you can see here, a conflict has occured. Manually resolve it and proceed with committing the change.

$ git add sample.txt
  $ git commit

Squash commits with rebase

For this tutorial step, we have prepared a repository with some ready made commits to speed things up.

You can download the repository here.

Go to the downloaded “stepup-tutorial/tutorial5” directory and examine the history of this repository. It should look like the following.

In this step, we are going to combine the two commits “append description of the commit command” and “append description of the pull command” into a single commit.

Current history

In order to do that, we will use “rebase -i”.

$ git rebase -i HEAD~~

Your default text editor should open and you will be on rebase interactive mode showing commits from HEAD to HEAD~~ as shown below.

pick 9a54fd4 append description of the commit command
  pick 0d4a808 append description of the pull command
  
  # Rebase 326fc9f..0d4a808 onto d286baa
  #
  # Commands:
  #  p, pick = use commit
  #  r, reword = use commit, but edit the commit message
  #  e, edit = use commit, but stop for amending
  #  s, squash = use commit, but meld into previous commit
  #  f, fixup = like "squash", but discard this commit's log message
  #  x, exec = run command (the rest of the line) using shell
  #
  # If you remove a line here THAT COMMIT WILL BE LOST.
  # However, if you remove everything, the rebase will be aborted.
  #

On the second line/commit, change the word “pick” to “squash”, then save and quit. The editor will now prompt you to edit the commit message of this newly formed commit. Edit the commit message, then save and quit.

The previous two commits are now quashed into a single new commit. You can verify the result by checking the history log using the log command.

organize commit

Change commit using rebase

For this tutorial step, we have prepared a repository with some ready made commits to speed things up.

You can download the repository here.

Go to the downloaded “stepup-tutorial/tutorial6” directory and examine the history of this repository. It should look like the following.

We are going to amend the commit with the message “append description of the commit command”.

Current history

Pass in the commit you wish to amend when calling rebase -i.

$ git rebase -i HEAD~~

Your default text editor will open listing commits from HEAD down to HEAD~~ as shown below.

pick 9a54fd4 append description of the commit command
  pick 0d4a808 append description of the pull command
  
  # Rebase 326fc9f..0d4a808 onto d286baa
  #
  # Commands:
  #  p, pick = use commit
  #  r, reword = use commit, but edit the commit message
  #  e, edit = use commit, but stop for amending
  #  s, squash = use commit, but meld into previous commit
  #  f, fixup = like "squash", but discard this commit's log message
  #  x, exec = run command (the rest of the line) using shell
  #
  # If you remove a line here THAT COMMIT WILL BE LOST.
  # However, if you remove everything, the rebase will be aborted.
  #

On the first line/commit, change the word “pick” to “edit”, then save and quit. The following output will be displayed and you will be checked out to that commit.

Stopped at d286baa... append description of the commit command
  You can amend the commit now, with
  
          git commit --amend
  
  Once you are satisfied with your changes, run
  
          git rebase --continue

Open the file sample.txt and make the change as shown below.

Git commands even a monkey can understand
  add: Register a change in an index
  Commit: Record index state.
  pull: Obtain the content of the remote repository

Use commit –amend to make the change.

$ git add sample.txt
  $ git commit --amend

You will now need to execute “git rebase –continue” to proceed with completing the rebase process.

$ git rebase --continue

While running a rebase on your current brach, you may run into conflicts in your changes. In that case, you will want to manually resolve those conflicts, then run “add” and “rebase –continue”. You would only want to resolve conflicts at this point, and there is no need to issue any new commits.

If you would like to stop rebasing however, you can call “rebase –abort” which will revert and exit the entire rebase process.

If done correctly, the commit should now be successfully amended.

In cases where you specify “edit” on more than a single line when calling “git rebase -i”, you will be prompted to amend each of the commits one at a time.

ORIG_HEAD points to the original commit before rebase actually takes place. This may come in handy especially when you accidentally issue a rebase. You can restore the previous history state by executing a rebase to ORIG_HEAD.

Merge –squash

For this tutorial step, we have prepared a repository with some ready made commits to speed things up.

You can download the repository here.

Go to the downloaded “stepup-tutorial/tutorial7” directory and examine the history of this repository. It should look like the following.

In this step, we are going to squash commits from the “issue1” branch to a single commit and merge it into the master branch.

Current history

Switch over to the master branch. Execute a merge with the option –squash like below.

$ git checkout master
  Switched to branch 'master'
  $ git merge --squash issue1
  Auto-merging sample.txt
  CONFLICT (content): Merge conflict in sample.txt
  Squash commit -- not updating HEAD
  Automatic merge failed; fix conflicts and then commit the result.

It looks like Git has detected a conflict. Let’s manually resolve that in sample.txt and proceed with committing the change.

$ git add sample.txt
  $ git commit
  [master 0d744a7] Conflicts:   sample.txt
    1 files changed, 4 insertions(+), 0 deletions(-)

We now have a new commit added to the master branch which includes all of the commits in the “issue1” branch. You can verify the new change in the revision history using the log command.

Modifying a branch

In the repository, create the following js file.

// sort.js
  var number = [19, 3, 81, 1, 24, 21];
  console.log(number);

Once you have created the file, push it to a remote branch. Learn how to push to a remote repository.

Now, we’ll walk through how to modify a development branch:

1. Create a branch

First create a branch to work on called “add-sort-func” to sort an array.

$ git checkout -b add-sort-func

Learn how to create a branch.

2. Modify the file and commit

Modify the file as follows.

// sort.js
  var sortNumber = function (number) {
    number.sort(function (a, b) {
      if (a == b) {
        return 0;
      }
      return a < b ? -1 : 1;
    });
  };
  
  var number = [19, 3, 81, 1, 24, 21];
  sortNumber(number);
  console.log(number);

Commit when the modification is completed.

$ git add sort.js
  $ git commit -m "<commit_message>"

3. Push the modified branch

When a commit is complete, push it to a remote branch.

$ git push origin add-sort-func

Create a pull request

Select the target repository from the Git repository list, and open a branch list.

There is the “add-sort-func” branch created earlier. Click “Add” in the pull request column.

The following screen will be displayed.

  1. Target branch: Target branch to merge a pull request
  2. Pull request branch: Branch to be merged
  3. Pull request contact: Person in charge of review and merge of the pull request created

Once you have entered the info, click the “Add pull request” button to create a pull request. When you create the pull request, notifications are sent to the pull request contact and the users you want to notify. The following screen will be displayed next for you to check the request.

Review and merge

You can check and review code differences in Backlog. Reviewers can check the changes made from the “File” tab.

If you find things that need to be modified, you can comment on the source code. Click the plus button that appears on the target row when you mouse over.

Enter what you want to be modified and the users you want to inform. Then click “Register”.

Your comments are embedded inline in the source code and also posted to the “Comment” tab.

Review the content, and modify the source code accordingly.

var sortNumber = function (number) {
    number.sort(function (a, b) {
        if (a === b) {
            return 0;
        }
        return a < b ? -1 : 1;
    });
  };
  
  var number = [19, 3, 81, 1, 24, 21];
  sortNumber(number);
  console.log(number);

Now that the correction is complete, commit and push again.

$ git add sort.js
  $ git commit -m "<commit_message>"
  $ git push origin add-sort-func

“Fix to use the strict equality operator (===)”

Comment on the pull request created earlier to indicate that it’s fixed.

Merge conflicts

During some merge conflicts, the source code will not be able to be merged automatically. You’ll need to manually fix the issue as follows.

1. Create the initial state

First, we need to reproduce the situation where the conflict occurs. We can make a conflict happen by using the equality operator (==) for one branch of sort.js and the strict equality operator (===) for the other.

Create a repository for testing as in the previous procedure, and push the following source code to the master branch.

// sort.js
  var number = [19, 3, 81, 1, 24, 21];
  console.log(number);

2. Create branch

Create two branches.

$ git checkout -b add-sort-func2
  $ git checkout -b add-sort-func1

3. Edit and push source code with add-sort-func1 branch

Edit the source code on the “add-sort-func1” branch.

// sort.js
  var sortNumber = function (number) {
      number.sort(function (a, b) {
          if (a == b) {
              return 0;
          }
          return a < b ? -1 : 1;
      });
  };
  
  
  var number = [19, 3, 81, 1, 24, 21];
  sortNumber(number);
  console.log(number);

When the modification is completed, commit and push it.

$ git add sort.js
  $ git commit -m "<commit_message>"
  $ git push origin add-sort-func1

“A process of sorting an array has been added”

4. Make a pull request for the add-sort-func1 branch and merge

Make a pull request and merge.

5. Edit and push source code with add-sort-func2 branch

Switch the branch to “add-sort-func2”.

$ git checkout add-sort-func2

Edit the source code.

// sort.js
  var sortNumber = function (number) {
      number.sort(function (a, b) {
          if (a === b) {
              return 0;
          }
          return a < b ? -1 : 1;
      });
  };
  
  var number = [19, 3, 81, 1, 24, 21];
  sortNumber(number);
  console.log(number);

When the modification is completed, commit and push it.

$ git add sort.js
  $ git commit -m "<commit_message>"
  $ git push origin add-sort-func2

“A process of sorting an array has been added”

6. Create a pull request for add-sort-func2 branch

7. A conflict occurs.

Resolving conflicts

When a conflict occurs, you can merge branches manually. Let’s merge the branch that you’re working on and which is the target branch for the pull request to be pulled (in this case, master branch).

1. Pull master branch

$ git pull origin master

2. Resolve the conflict locally

// sort.js
  var sortNumber = function (number) {
      number.sort(function (a, b) {
  <<<<<<< HEAD
        if (a === b) {
  =======
        if (a == b) {
  >>>>>>> 839396c5383737ec06b9c2a842bfccc28f3996ef
            return 0;
        }
        return a < b ? -1 : 1;
      });
  };
  
  var number = [19, 3, 81, 1, 24, 21];
  sortNumber(number);
  console.log(number);

Above ======= is the local repository, and below is the remote repository. This time, keep the code of the local repository and delete the remote repository because the former will make a better code.

// sort.js
  var sortNumber = function (number) {
      number.sort(function (a, b) {
          if (a === b) {
              return 0;
          }
          return a < b ? -1 : 1;
      });
  };
  
  var number = [19, 3, 81, 1, 24, 21];
  sortNumber(number);
  console.log(number);

3. Commit and push the modified source code again

$ git add sort.js
  $ git commit -m ""
  $ git push origin add-sort-func2
  "Conflict resolved"

4. The conflict has been resolved.

There is no longer a conflict and you can now merge.

Related

Git Reference

Git Reference

Learn Git Collaboration

Learn Git Collaboration

Subscribe to our newsletter

Learn with Nulab to bring your best ideas to life