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

val*_*dil 7 git alias git-config

每当我尝试打字时,git stash list都会流氓和打字git stash ls.我真的想将ls列为别名,但仅限于stash子命令.这可能与git别名?

jub*_*0bs 8

Git没有提供任何子命令别名的机制; 请参见git-config手册页.

但是,有一个技巧可以实现相同的效果:git通过定义一个也git可以执行所需的shell命令,在二进制文件周围使用一个小包装器:

git() {
    if [ "$1" = "stash" -a "$2" = "ls" ]
    then
        command git stash list
    else
        command git $@
    fi;
}
Run Code Online (Sandbox Code Playgroud)

不漂亮,但做的工作(在我的一个存储库中测试):

# 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
Run Code Online (Sandbox Code Playgroud)

请注意,这种方法不是很强大.特别地,git stash list被如果有之间的其他命令行参数运行gitstash ls,如在

git -C ~/Desktop stash ls
Run Code Online (Sandbox Code Playgroud)

不过,这种方法应该足以满足您的使用需求.

为避免git每次启动shell时都必须重新键入该函数的定义,应将其放在shell配置为源的其中一个文件中.