Chapter 8: git branch

Creating a new repo

face Josiah Wang

We can finally start creating git branches for real.

Just to get you comfortable with branches, let us try playing with branches in the branchtest repo (or whatever you named it) you have created a while ago. If you did not create this earlier, do this now!

We now have a blank repo to play around with.

If you type git branch, you will not get anything. Obviously, you have not committed anything yet!

user@MACHINE:~/branchtest$ git branch
user@MACHINE:~/branchtest$

Now, let’s do our first commit. Treat this as a refresher!

Now create a file. I will call it python.txt (you can choose your own name).

Then edit the file, and type in whatever you like (I’ll just type a single a)

a

Now, add your git identity to the repo, and then add and commit this file to the repo.

user@MACHINE:~/branchtest$ git config user.name "Josiah Wang"
user@MACHINE:~/branchtest$ git config user.email "my.email@imperial.ac.uk"
user@MACHINE:~/branchtest$ git add python.txt
user@MACHINE:~/branchtest$ git commit -m "Initial commit"
[main (root-commit) 620496e] Initial commit
 1 file changed, 1 insertion(+)
 create mode 100644 python.txt
user@MACHINE:~/branchtest$ git status
On branch main
nothing to commit, working tree clean
user@MACHINE:~/branchtest$ git log --oneline
620496e (HEAD -> main) Initial commit
user@MACHINE:~/branchtest$ git branch
* main

As you can see, you are now on the main branch, which is also the HEAD branch. So any files in your working directory is from this branch.

Now we’ll try to do a second commit. Edit python.txt again, and add something else to the file. I’ll add a b in the second line.

a
b

Save python.txt, and add/commit again.

user@MACHINE:~/branchtest$ git add -u
user@MACHINE:~/branchtest$ git commit -m "Added b to python.txt"
[main 6ca445c] Added b to python.txt
 1 file changed, 1 insertion(+)
user@MACHINE:~/branchtest$ git log --oneline
6ca445c (HEAD -> main) Added b to python.txt
620496e Initial commit

You can see from the log that the main branch is now pointing to the latest commit, and HEAD is pointing to the main branch.