Back To The Basics: Git Init & Git Branches
If you’re starting up a git repository, you’ll need to able to initialize it. That means you’re creating an empty git repository which is a directory called .git which has directories within it called objects, refs and a few other files and directories. It also creates a HEAD file which references the HEAD of the master branch that is created. Let’s see some commands:
> git init
> ls -a
.git
> cd .git
> ls
HEAD
branches
config
description
hooks
info
objects
refs
The thing we want to focus on is the branches directory. When we first make a git repository, it puts us on the master branch. Picture it like a tree. So right now, the master branch is the only and single branch of our tree. Let’s add a file and commit that file to our branch:
> touch myFile.md
> git add myFile.md
> git commit -m 'adding an empty markdown file'
[master (root-commit) 7c5ab19] adding an empty markdown file
1 file changed, 0 insertions(+), 0 deletions(-)
create mode 100644 myFile.md
> git status
On branch master
nothing to commit, working tree clean
If we then create a new branch it’ll make a new branch off of the master branch, which means whatever we did in the master branch will be in our new branch as well:
> git checkout -b new-branch
> ls
myFile.md
Let’s make a new file on our new-branch
:
> touch otherFile.md
> git add otherFile.md
> git commit -m 'adding another file'
[test 744196a] adding another file
1 file changed, 0 insertions(+), 0 deletions(-)
create mode 100644 otherFile.md
> ls
myFile.md otherFile.md
Now, let’s switch back to our master branch:
> git checkout master
> ls
myFile.md
Notice that the master branch does not have otherFile.md. Why not? This is because now our master branch and our new-branch are two totally separate entities. Even though we branched new-branch off of our master branch it is now independent and will not contain any similarities once it has been branched off.
This is a very powerful and important concept and feature of git: being able to have two (or more) totally separate versions of your repository that are independent and can be tracked with different files and states.
Read more about git-init and git checkout