如何在 git 别名中使用 bash 函数?

pla*_*etp 11 git bash alias config function

我想在 git 别名中使用 bash 函数。所以我将其添加到我的.bashrc

fn() {
    echo "Hello, world!"
}
export -f fn
Run Code Online (Sandbox Code Playgroud)

以及我的.gitconfig

[alias]
    fn = !fn
Run Code Online (Sandbox Code Playgroud)

但随后git fn会产生错误:

fatal: cannot run fn: No such file or directory
fatal: While expanding alias 'fn': 'fn': No such file or directory
Run Code Online (Sandbox Code Playgroud)

这是在 git 别名定义中使用 bash 函数的正确方法吗?

hug*_*aka 11

那是因为 git 使用/bin/sh(所以你的.bashrc没有来源)。

您可以按照此答案中指定的 git 别名调用 bash 。

问题是由 git 命令启动的 bash shell 没有加载你的.profile(这是负责包含 的.bashrc)。

可能还有其他方法可以做到这一点,但您可以通过执行以下操作来解决:

[alias]
    fn = !bash -c 'source $HOME/.my_functions && fn'
Run Code Online (Sandbox Code Playgroud)

像这样的文件.my_functions

#!/bin/bash
fn() {
    echo "Hello, world!"
}
Run Code Online (Sandbox Code Playgroud)

如果您希望从常规 shell 中使用这些功能,您甚至可以从.my_functions您的源代码中获取这些功能。.bashrc


Cha*_*ffy -1

如果您想 100% 确定导出的函数会受到尊重,请确保调用的 shell 是 bash,而不是/bin/sh(如果由 ash 或 dash 实现,则不会尊重它们)。

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

...正确发出:

hello, world
Run Code Online (Sandbox Code Playgroud)

相关条目.gitconfig

[alias]
    fn = !bash -c 'fn \"$@\"'
Run Code Online (Sandbox Code Playgroud)