Git: create a new empty branch with no history or commits

If you need to create a new git branch for your project, one that is completely fresh and with no previous history or commits, that can be done using the “orphan” flag of the switch command if you are using git 2.23+.

Fresh branch using ‘git switch’

# create fresh branch
git switch --orphan my-fresh-branch

# validate, no commit history on this branch
git log

# commit and push
git commit -a -m "initial commit of my-fresh-branch" --allow-empty
git push -u origin my-fresh-branch

Fresh branch using older ‘git checkout’

If you are using a git client older than 2.23, use ‘git checkout’ like below.

# create fresh branch
git checkout --orphan my-fresh-branch2
# checkout will not remove the files, so you must do this step manually
git rm -rf .

# commit and push
git commit -a -m "Initial commit on my-fresh-branch2" --allow-empty
git push -u origin my-fresh-branch2

Merging this fresh branch into another branch

If you want to merge this fresh branch into another, it will require the flag “allow-unrelated-histories”.

git checkout main

# this will fail! 'refusing to merge unrelated histories'
git merge my-fresh-branch

# this will succeed
git merge my-fresh-branch --allow-unrelated-histories

 

REFERENCES

git switch man page

stackoverflow,com, create empty branch on github

stackoverflow, difference between git checkout and switch

github git, release notes for 2.23.0 where switch was introduced

stackoverflow, is there way of introducing unrelated branch