bt93ia
Last Updated: November 26, 2016
·
9.552K
· jeffremer
372909bbd2c8ec9f54a401c368789335

Extend Git with Custom Commands

You can extend and customize git through command aliases. You can also add entirely new commands.

Place any executable with a name like git-squash in your PATH and git will automatically make it available as a subcommand.

You can then call it just like any other git command.

$ git squash 3

The git executable places precedence with it's own commands in ls $(git --exec-path), the GITEXECPATH environment variable, and the $(gitexecdir) from the git Makefile during build/install time, so make your command name is unique. That's how projects like git-flow extend git.

Turns out git provides a library of shell functions expressly for this purpose, at $(git --exec-path)/git-sh-setup. Use it in your own shell scripts like:

source "$(git --exec-path)/git-sh-setup"

After that you'll have access to a handful of shell functions that perform useful actions and sanity checks or give you access to git information such as handy usage and die methods.

For example:

git-squash

#!/bin/sh

source "$(git --exec-path)/git-sh-setup"

USAGE="COMMITS"
function _squash() {
    if [[ $# == 1 ]]; then
        if [[ -n $(git rev-parse --verify --quiet HEAD~$1) ]]; then
            git rebase -i HEAD~$1
        else
            die "HEAD~$1 does not exist"
        fi
    else
        usage
    fi  
}

_squash $1

In fact many of the executables that ship with git are just shell scripts, such as git bisect and even git rebase.

2 Responses
Add your response

22845
B324c89a67b7de17eb21481652c61c14

Thanks! it was useful. Git's approach seems really smart. I am wondering if that's some common pattern for unix programs since never saw it before

over 1 year ago ·
28344

how to make this new command auto complete in zsh?

4 months ago ·