How to use a bash function in a git alias?

2020-02-14 08:14发布

I want to use a bash function in a git alias. So I added this to my .bashrc:

fn() {
    echo "Hello, world!"
}
export -f fn

and to my .gitconfig:

[alias]
    fn = !fn

But then git fn produces an error:

fatal: cannot run fn: No such file or directory
fatal: While expanding alias 'fn': 'fn': No such file or directory

Is this a correct way to use a bash function in a git alias definition?

3条回答
太酷不给撩
2楼-- · 2020-02-14 08:53

If you want to be 100% certain that exported functions will be honored, ensure that the shell being called is bash, not /bin/sh (which will not honor them if it's implemented by ash or dash).

fn() { echo "hello, world"; }
export -f fn
git config --global alias.fn $'!bash -c \'fn "$@"\' _'
git fn

...properly emits:

hello, world

The relevant entry in .gitconfig:

[alias]
    fn = !bash -c 'fn \"$@\"'
查看更多
不美不萌又怎样
3楼-- · 2020-02-14 09:05

I don't know why, but if I just put a space before the function name in .gitconfig, it works without a problem and outputs the message:

[alias]
    fn = ! fn

It might be a bug in git, or I'm missing something in the documentation.

查看更多
该账号已被封号
4楼-- · 2020-02-14 09:09

Thats because git uses /bin/sh (so your .bashrc is not sourced).

You can call bash in a git alias as specified in this answer.

The thing is the bash shell started by the git command is not loading your .profile (which is the one responsible for including the .bashrc).

There may be other ways to do it but you can work around by doing:

[alias]
    fn = !bash -c 'source $HOME/.my_functions && fn'

With the file .my_functions like this:

#!/bin/bash
fn() {
    echo "Hello, world!"
}

You can even source .my_functions into your .bashrc if you want the functions to be available from regular shells.

查看更多
登录 后发表回答