Pushing a (New) Empty Branch

May 12, 2020

Yesterday, I invoked this fun little command to create a new, empty dist branch in a GitHub repository:

commit_id=$(git commit-tree -m 'Distribution branch' 4b825dc642cb6eb9a060e54bf8d69288fbee4904)
git push origin ${commit_id}:refs/heads/dist

But I didn't explain it. So today I wanted to unpack exactly what's going on here.

First, we're going to run a git command called git commit-tree, which will create a commit from a given tree object. The -m 'Distribution branch' will set the message on the commit. And the 4b825dc642cb6eb9a060e54bf8d69288fbee4904 is a special tree, the empty tree. It has no files in it; it's completely empty, and it's hardcoded into Git clients so it will just always be magically available to you. Since we didn't specify any parents, the new commit will not have any (it will be a new branch, completely unrelated to any existing branches). The new commit ID will be output on standard out.

Then, we're using the bash/zsh syntax $( ... ). This indicates that we want to run that git command that's enclosed inside of them and capture it's standard out...

Next, the commit_id=... will take that output and set it as the value of a variable. So we'll end up with the new git commit ID of the empty commit that we just created

Finally, you can push up a single git commit to a remote server, creating a new branch when you do. You can use the <source>:<target> syntax for this, but pushing a new branch from a commit requires you to specify the complete reference name, in other words refs/heads/dist instead of just the branch name dist.

So, voila! Now you can push an empty commit to a new branch on GitHub without having to switch branches, worry about what you have committed, or otherwise change anything in your local repository.