I would like to completely empty the master branch in Git. For now, I would also like to keep all other branches which have been branched from master.
Is this possible and how?
Delete a branch with git branch -d <branch> . The -d option will delete the branch only if it has already been pushed and merged with the remote branch. Use -D instead if you want to force the branch to be deleted, even if it hasn't been pushed or merged yet. The branch is now deleted locally.
To delete all branches in Git except main, simply replace the grep for master with a grep for main: git branch | grep -v "main" | xargs git branch -D. git branch | grep -v " main$" | xargs git branch -D.
Can the master branch be deleted? The master branch is just a type of branch in the repository, which is also the default branch by default. But, as a rule in Git, default branches cannot be deleted. So, to delete the master branch first, the user has to change the default branch.
That's actually called "delete old master branch and create new from scratch"
This will create a new master branch pointing to initial commit:
git branch -D master git checkout -b master <initial commit hash>
This will create a totally new master branch unrelated to whatever you had:
git branch -D master git checkout --orphan master git rm -rf *
But actually you can simply save current repository to some other place and create a new repository instead.
First, you need to move or delete your current master branch. Personally, I prefer to move it aside rather than delete it. After that, you simply create a new branch with no parents by using the --orphan
flag. For example:
git branch -m master old_master git checkout --orphan master
Since the current branch now has no history, some commands may fail with errors like fatal: bad default revision 'HEAD'
until after you make your first commit on the new master branch. This is normal, and is the same behavior you see in freshly-initialized repositories.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With