Create Clean Branch in Git

Development1 min read

Normally, whenever you create a new branch, you need the original branch and then you branch them. The problem is, they have a parent branch. The commit history from the original branch will be carried to your new branch too. This is intentional and not the git issue. That how git branch supposed to be work.

SourceTree new Branch

Normally, you don’t need to create a completely new branch. Rather, you create a new repository. It new project anyway, so it best to use a different repository. Or maybe just change it gradually.

But, sometimes you need or want to create a completely new branch without any parent but still in the same repository. For whatever your reason is.

You may don’t know this yet, but git has a command to checkout new branch without any parent. It called the orphan branch. With this command, you can create a completly new branch and its root won’t have any connection to the other branch. But it will still have previous files in the repository directory. Don’t worry about that, you can remove it later after the checkout process is done.

So in short, what you want to do is to create a new orphan branch, clear the file and remove file history and then add the new file for your new project. Here is how to do it.

First, create a new orphan branch. It has the same command as git checkout but with the --orphan parameter.

git checkout --orphan <newbranch>

Second, you want to remove any old file in the repository directory. Either you delete it using file explorer, command or by any method you prefer. If you are using git rm command, it may look like this.

git rm --cached -r .

Dot “.” character at the end of the command is intentional. That mean it will remove any files from the current directory which is your repository directory. -r parameter mean is it will remove recursively to ensure any files is deleted.

And that it. Simple right?

If you have any further question or suggestion, you can ask me in the comment bellow. Thank you for reading!