使用管道添加 git 别名会抱怨配置错误

Adding git alias with pipes complains about wrong configuration

我正在尝试添加一个 git 别名,让我中止刚刚完成的变基。我试图在 .gitconfig:

中添加这个
rebabort = !sh -c 'git reflog | grep -v rebase | head -1 | sed -e "s/^\([[:alnum:]][[:alnum:]]*\)\(.*\)//g" | git reset --hard'

但它抱怨配置错误。无论如何,我尝试通过以下方式添加别名:

git config alias.rebabort '!git reflog | grep -v rebase | head -1 | sed -e "s/^\([[:alnum:]][[:alnum:]]*\)\(.*\)//g" | git reset --hard'

它奏效了。我错过了什么?

更新

我也试过在.gitconfig

中添加这个
rebabort = "!f() { \
                git reflog | grep -v rebase | head -1 | sed -e 's/^\([[:alnum:]][[:alnum:]]*\)\(.*\)//g\' | git reset --hard;
    }; f"

还有这个

rebabort = !"git reflog | grep -v rebase | head -1 | sed -e 's/^\([[:alnum:]][[:alnum:]]*\)\(.*\)//g' | git reset --hard"

但它仍然抱怨配置错误。

我复制了你的 "line that worked" 然后查看了我的虚拟项目的 .git/config 并发现了以下内容:

[alias]
        rebabort = !git reflog | grep -v rebase | head -1 | sed -e s/^\([[:alnum:]][[:alnum:]]*\)\(.*\)/\1/g | git reset --hard

只需将其复制到您的 ~/.gitconfig

看起来不需要 sh -c 东西很简单。你的 .gitconfig 不是 .bashrc;我这样说是因为看起来您正在尝试以 .bashrc 格式编写别名。

此外,为了您的参考,您可以执行以下操作以获得相同的效果(您的行有效,加上 --global)选项,因为 --global 通常会添加到您的 ~/.gitconfig:

git config --global alias.rebabort '!git reflog | grep -v rebase | head -1 | sed -e "s/^\([[:alnum:]][[:alnum:]]*\)\(.*\)//g" | git reset --hard'

git config 的帮助文件对于学习新选项和技巧也非常有用。 https://git-scm.com/docs/git-config