Faster git'ing and less typing with custom bash functions

Are you using git often in your shell? Then you may find the following bash functions helpful which safe you from repetitive typing and thus reduce your time spent in the command line. You can put these functions into your ~/.bashrc file (or equivalent) so that they are readily available every time you open a terminal. And rename the functions to your desire, depending on what command you want to type to invoke them!

Note that fzf needs to be installed for these commands which is used for (multi-)selection of branches.

1. Deleting a single or many branches at once without typing a single name

When you want to get rid of a local branch, for example after merging it, this bash functions allows you to multi-select all branches to delete. Select any branch to delete using your arrow keys, hit Tab key to mark them and Enter to confirm. Just a single branch to delete? Simple select it via arrow keys and hit Return.

function db() {}
  git rev-parse --is-inside-work-tree 1>/dev/null || return
  git branch -d $(test -n "$1" && echo "$@" || (git branch | grep -v \* | fzf -m))
}

Example calls:

> db                       # Shows a list of available branches (except the
                           # currently checked out one) to pick from.
                           # Use <Tab> key to delete multiple branches at once.
> db cool-branch           # Deletes the local branch named `cool-branch`

2. Switching to another branch (also known as “check out”) without typing its name

Want to work on another branch? Type sw to switch!

function sw() {
  git rev-parse --is-inside-work-tree 1>/dev/null || return
  git switch $(test -n "$1" && echo "$@" || (git branch | grep -v \* | fzf))
}

Example calls:

> sw                       # Shows a list of branches to select from
> sw master                # Switches to the master branch
> sw -c cool-branch        # Creates a new branch "cool-branch" and switches to it
comments powered by Disqus