DEV Community

Zanets
Zanets

Posted on

Custom git command

There is an 'alias' section in gitconfig to create custom command.

[alias]
    ck = checkout

You can type git ck instead of git checkout.

But the most powerful of alias is it also accept shell script.

test = "! echo git-test"

Now we can have a lot of fun.
You can just write a tiny script in gitconfig like this

test = "! \
    f() { \
        echo git-test-start; \
        echo $1; \
        echo git-test-end; \
    }; f"

Bascally I create a function and call it immediatly. Wrap in a function so that we can use $@, $1... to access arguments.

But since alias needs to be a single line, you need ; \ at each end of line. It's fine for simple script but painful for complex one. So I came out with another approach

test = "! ~/bin/git.sh do_test"

And create ~/bin/git.sh

#!/usr/bin/env bash

do_test() {
    echo git-test-start
    echo $1
    echo git-test-end
}

"$@"

Then don't forget chmod +x ~/bin/git.sh.

That's it. It's very useful for those complex and hard to remember tricks of git.

Top comments (0)