Learn Git - Branch, Checkout, Merge

Question Click to View Answer

Make a directory called git_test

$ mkdir git_test

Change to git_test directory

$ cd git_test

Make sure you are in the right directory

$ pwd  # /Users/username/Desktop/git_test

Initialize and empty git repository

$ git init

Create a text file called readme.txt

$ touch readme.txt

Open readme.txt file with your text editor and add two lines of text: This is the first line of text This is the second line of text

Check the git status

$ git status

Notice that you are on the master branch and that changes have not been committed yet

Add the files to be committed

$ git add readme.txt

Make your first commit

$ git commit -m “first commit”

This is a commit to the master branch because you are placed on the master branch by default and never switched off of it.

Updated the readme.txt file and add the following text in lines 3 and 4: This is the third line of text This is the fourth line of text

Check Git status to verify that you have made changes.

$ git status

Add the changes and make a second commit

$ git add .
$ git commit -m “Second commit”

Create a new branch called temp

$ git checkout -b temp

Verify that you are now on the temp branch

$ git branch

You can determine the branch you are on from the git status command as well

Add another line of text to readme.txt

This is a fifth line of text

Note that this change was made while on the temp branch

Add and commit this change to the temp branch

$ git add .
$ git commit -m “Third commit”

Critical point: these changes are being made to the temp branch and not the master branch

Run a command to show the commits that have been made to the temp branch

$ git log

Switch to the master branch

$ git checkout master

Open the readme.txt file and see if there are any changes.

The line “This is a fifth line of text” has disappeared.  This change was only made to the temp branch, not the master branch, so it is not showing up.

Add a line to the readme.txt file and then throw out all changes since the last commit

$ git reset --hard

Open the readme.txt file and see that the fifth line of text has been deleted

We are still on the master branch.  Merge the changes from the temp branch on to the master branch (remember that the temp branch had 5 lines of text in the readme.txt file)

$ git merge temp

Look at the readme.txt file and see that all 5 lines now appear

Type in git status and notice that the changes are automatically committed when you merge

$ git status