89

我可以嵌入以下 bash shell 代码:

for name in $(git diff --name-only $1); do git difftool $1 $name & done

直接进入创建一个git别名:

git config --global alias.diffall ***my-bash-code-here***

这源于我之前关于 SO 的问题/答案,我将代码放入 .sh 文件中,然后为该文件添加别名:

git config --global alias.diffall '!sh diffall.sh'

但是在对简单性的永无止境的追求中,必须有一种方法可以跳过文件并将代码直接插入别名中?看不懂格式。。。

4

5 回答 5

100
git config --global alias.diffall '!sh diffall.sh'

这在某种程度上是多余的。如果你无论如何都要把 'diffall.sh' 添加到你的 $PATH 中,为什么不把它保存为 'git-diffall',这样你就不用声明别名了。是的,“git diffall”会运行它。

于 2009-08-21T01:29:58.207 回答
39

要在 git 别名中运行命令,尤其是向这些命令传递参数,您可能必须创建一个临时函数,然后立即调用该函数:

$ vim ~/.gitconfig
...
[alias]
    # compare:
    foo = "! echo begin arg=$1/$2/end"
    foo2 = "!f() { echo "begin arg=$1/$2/end"; }; f"

在这个例子中,这个函数可能是你所需要的(并且对于你可以在单个“语句”中做什么也更加灵活);而且您可能会说,对于这两个选项,git 命令的剩余参数只是作为参数传递给别名,无论它是“echo”还是“f”;调用该函数只会消耗 args,而忽略未明确使用的内容:

$ git foo a b c
begin arg=a/b/end a b c

$ git foo2 a b c
begin arg=a/b/end

另一个示例(根据匹配模式列出所有别名)(注意:您可以在整个 .gitconfig 中继续重用相同的函数名称“f()”):

[alias]
    alias = "!f() { git config --get-regexp "^alias.${1}$" ; }; f"

第一个返回“foo$”的别名,第二个返回“foo.*”的别名:

$ git alias foo
alias.foo ! echo begin arg=$1/$2/end

$ git alias 'foo.*'
alias.foo ! echo begin arg=$1/$2/end
alias.foo2 !f() { echo begin arg=$1/$2/end; }; f

(注意:实际结果可能因 shell 而异;我在 Linux、Unix 和 Cygwin (Windows) 上将其与 bash 一起使用。)

于 2013-02-21T05:04:57.373 回答
27

我在文档中找不到,但如果你在路径中创建一个脚本“git-<name>”,你可以在你的仓库中用“git name”调用它。

看:

$ cd ~/bin
$ echo "echo I love this log:
>pwd
>git log --graph  --summary --decorate --all" > git-logg
$ chmod +x git-logg
$ cd /path/to/your/repo
$ git logg
I love this log:
/path/to/your/repo
* commit 3c94be44e4119228cc681fc7e11e553c4e77ad04 (whatever-branch)
| Author: myself <my@Laptop.(none)>
| Date:   Fri Apr 1 16:47:20 2011 +0200
| 
|     would have been better not to do it at all
| 
...
$

因此,您也可以使用这种(相当晦涩)的方式编写您喜欢的任何别名。

您甚至可以将自动完成添加到定义函数的新命令中。信息在这里

$ _git_logg ()
{
  # you can return anything here for the autocompletion for example all the branches
  __gitcomp_nl "$(__git_refs)" 
}
于 2011-07-16T19:29:30.890 回答
15

将这两行添加到您的 .git/config 文件中应该可以解决问题。

[alias]
    diffall = '!for name in $(git diff --name-only $1); do git difftool $1 $name & done'

编辑:大概 git-config 版本也可以,但我喜欢将我的别名保留在配置文件中以便于管理。

git wiki 上有一个很好的页面,它非常清楚地解释了别名:http: //git.or.cz/gitwiki/Aliases特别是,请阅读“带参数的高级别名”

于 2009-08-21T00:03:07.820 回答
-4

(来自 ProGit 文档:http ://progit.org/book/ch7-3.html )

您是否尝试在 .git/hooks 中添加脚本?

例如,如果您创建脚本 .git/hooks/post-checkout:

#!/bin/bash

echo "This is run after a 'git checkout'"

然后运行命令:

$ git checkout master
Switched to branch 'master'
This is run after a 'git checkout'
于 2011-12-05T13:01:25.020 回答