Chapter 8: git branch

Creating a new branch

face Josiah Wang

Now, let say you have a killer idea you want to experiment with.

But you do not want to mess up what you have done so far, in case your killer idea turns out to be rubbish 😢 The main branch is where you want your proudest work to be displayed!

So, this is a good time to create a new branch to experiment with your killer idea. Let’s call this new branch killer (or whatever you fancy).

user@MACHINE:~/branchtest$ git branch killer
user@MACHINE:~/branchtest$ git branch
  killer
* main

git branch now shows that you have two branches (and you are currently still in the main branch indicated by the *).

Let’s now switch to the new branch. We will use git checkout for this.

user@MACHINE:~/branchtest$ git checkout killer
Switched to branch 'killer'
user@MACHINE:~/branchtest$ git branch
* killer
  main

The HEAD is now pointing to killer.

checkout will change the HEAD to point to the branch you specified. It will also update the files in your working directory (branchtest) to reflect the latest commit of the killer branch.

Now, create a new file called idea.txt, and just fill it up with whatever you like. Then add+commit as usual. Remember that you will now committing to the killer branch, not main.

user@MACHINE:~/branchtest$ git add idea.txt
user@MACHINE:~/branchtest$ git commit -m "Added a new file idea.txt"
[killer 9d34c0a] Added a new file idea.txt
 1 file changed, 3 insertions(+)
 create mode 100644 idea.txt
user@MACHINE:~/branchtest$ ls
idea.txt  python.txt

If you do git log, you can now see that the killer branch points to the latest commit, while the main branch points to the previous commit. And killer is currently the HEAD branch.

user@MACHINE:~/branchtest$ git log --oneline
9d34c0a (HEAD -> killer) Added a new file idea.txt
6ca445c (main) Added b to python.txt
620496e Initial commit