Last Updated: February 25, 2016
·
1.556K
· koraktor

Git alias for really quick branching

This is a situation that you might already know:

You start working on a big, new feature and change maybe a handful of files to implement it. Before you commit your work on a new or existing feature branch, you notice that maybe one or more changes you just made aren't really isolated to your new feature, but maybe another feature, a bugfix or something else that doesn't really fit into your new branch.

Usually, one would commit the changes for the new feature and create another feature branch starting from your base branch. This might work well in most situations, but sometimes it would be really handy to just create a new branch with a small and isolated change before doing a clean, big commit to your actual feature branch. That way, you can easily merge, cherry-pick or

The following alias allows to instantly create a new branch with whatever is in the index:

$ git config -e --global

[alias]
    nb = "!sh -c 'git checkout -b $0 && { git commit $@ || { git checkout - && git branch -d $0 && false; }; } && git checkout -'"

For example:

$ git add some_broken_file.rb
$ git nb fix-broken-file

You can also use the usual arguments for git-commit. The first argument is always the name of the branch you want to create, all other arguments are passed to git-commit.

$ git nb patch-some-files -p
$ git nb new-branch -a -m "Create a new branch with all current changes"

Note:
The alias will also gracefully fail for existing branches or when you choose to abort your commit.