git alias shell 命令的错误

use*_*394 9 bash git shell-script

我在带有 git 1.7.1 的 cygwin 上使用 bash 版本 4.1.2(1)-release (x86_64-redhat-linux-gnu)。我想为需要使用输入参数两次的命令创建别名。按照这些说明,我写了

[alias]
branch-excise = !sh -c 'git branch -D $1; git push origin --delete $1' --
Run Code Online (Sandbox Code Playgroud)

我收到这个错误:

$> git branch-excise my-branch
sh: -c: line 0: unexpected EOF while looking for matching `''
sh: -c: line 1: syntax error: unexpected end of file
Run Code Online (Sandbox Code Playgroud)

我最后尝试了 a-和 a --,但我得到了同样的错误。我怎样才能解决这个问题?

Ark*_*zyk 11

man git-config 说:

语法相当灵活和宽松;空格大多被忽略。# 和 ; 字符开始注释到行尾,空白行被忽略。

所以:

branch-excise = !bash -c 'git branch -D $1; git push origin --delete $1'
Run Code Online (Sandbox Code Playgroud)

相当于:

#!/usr/bin/env bash

bash -c 'git branch -D $1
Run Code Online (Sandbox Code Playgroud)

运行上面的脚本打印:

/tmp/quote.sh: line 3: unexpected EOF while looking for matching `''
/tmp/quote.sh: line 4: syntax error: unexpected end of file
Run Code Online (Sandbox Code Playgroud)

一种解决方案是将整个命令放入"

branch-excise = !"bash -c 'git branch -D $1; git push origin --delete $1'"
Run Code Online (Sandbox Code Playgroud)

但是,它仍然不起作用,因为它$1是空的:

$ git branch-excise master
fatal: branch name required
fatal: --delete doesn't make sense without any refs
Run Code Online (Sandbox Code Playgroud)

为了使其工作,您需要在其中创建一个虚拟函数.gitconfig并像这样调用它:

branch-excise = ! "ddd () { git branch -D $1; git push origin --delete $1; }; ddd"
Run Code Online (Sandbox Code Playgroud)

用法:

$ git branch-excise  master
error: Cannot delete the branch 'master' which you are currently on.
(...)
Run Code Online (Sandbox Code Playgroud)

  • 值得注意的是:与 shell 不同的是,如果您不小心省略了 `ddd` 定义中的尾随分号,您也会遇到同样令人困惑的“语法错误:文件意外结束”错误。 (2认同)