Git 函数中的别名输出着色

Git alias output coloring in function

我想添加一个复杂的 git 别名,它会在执行命令时回显消息。我想给一些消息着色(红色表示错误等)。

[alias]
    test = !"f() { echo "3[31mHello3[0m World"; }; f"

然而,当我执行别名时出现错误:

bad config line X in file .gitconfig`

运行 终端中的相同命令 echo "3[31mHello3[0m World" 着色得很好。

必须转义反斜杠。来自 git-config 文档...

Inside double quotes, double quote " and backslash \ characters must be escaped: use \" for " and \ for .

The following escape sequences (beside \" and \) are recognized: \n for newline character (NL), \t for horizontal tabulation (HT, TAB) and \b for backspace (BS). Other char escape sequences (including octal escape sequences) are invalid.

这会起作用。

test = !"f() { echo \"\033[31mHello\033[0m World\"; }; f"

但是如果你的别名太复杂以至于你需要定义的函数会变成一团糟。我建议将这些函数放在它们自己的文件中并获取它。

test = !"source ~/.gitfuncs; f"

$ cat ~/.gitfuncs
f() { echo "3[31mHello3[0m World"; };