如何为 Git 子命令定义别名(例如,对于 `git stash list` 中的 `list`)?

How can I define an alias for a Git subcommand (e.g. for `list` in `git stash list`)?

每当我尝试输入 git stash list 时,我的手指就会乱用并输入 git stash ls。我真的很想给 ls 添加别名以列出,但只能在 stash 子命令中使用。 git 别名可以吗?

Git 不提供任何别名子命令的机制;请参阅 git-config 手册页。

但是,有一个技巧可以达到相同的效果:通过定义一个 shell 命令(也称为 git 来执行您想要的操作,在 git 二进制文件周围使用一个小包装器:

git() {
    if [ "" = "stash" -a "" = "ls" ]
    then
        command git stash list
    else
        command git $@
    fi;
}

不漂亮,但可以(在我的一个存储库中测试过):

# starting from a dirty working state...
$ git stash save
Saved working directory and index state WIP on master: 7c6655d add missing word in documentation
HEAD is now at 7c6655d add missing word in documentation
$ git stash ls
stash@{0}: WIP on master: 7c6655d add missing word in documentation

请注意,这种方法不是很可靠。特别是,如果 gitstash ls 之间还有其他命令行参数, 不会 成为 运行,如

git -C ~/Desktop stash ls

尽管如此,该方法应该足以满足您的用例。

为避免每次启动 shell 时都必须重新输入 git 函数的定义,您应该将其放入 shell 配置的文件之一来源。