2013-04-27 97 views
6

我试图做一个别名git commit它也记录到一个单独的文本文件的消息。但是,如果git commit返回"nothing to commit (working directory clean)",它不应该记录任何东西到单独的文件。字符串比较在PowerShell函数中不起作用 - 我做错了什么?

这是我的代码。 git commit别名的作品;输出到文件的作品。但是,无论从git commit中返回什么,它都会记录该消息。

function git-commit-and-log($msg) 
{ 
    $q = git commit -a -m $msg 
    $q 
    if ($q –notcontains "nothing to commit") { 
     $msg | Out-File w:\log.txt -Append 
    } 
} 

Set-Alias -Name gcomm -Value git-commit-and-log 

我使用PowerShell的3

回答

7

$q包含GIT中的stdout的每一行的一个字符串数组。如果你想测试部分字符串匹配尝试-match操作

$q -notcontains "nothing to commit, working directory clean" 

:要使用-notcontains你需要一个项目的全部匹配字符串数组中,例如。 (注意 - 它使用正则表达式,并返回匹配的字符串。)如果左操作数是一个数组

$q -match "nothing to commit" 

-match会工作。所以,你可以使用这个逻辑:

if (-not ($q -match "nothing to commit")) { 
    "there was something to commit.." 
} 

另一个选择是使用-like/-notlike运营商。这些接受通配符并且不使用正则表达式。匹配(或不匹配)的数组项将被返回。所以,你也可以使用这个逻辑:

if (-not ($q -like "nothing to commit*")) { 
    "there was something to commit.." 
} 
+1

”$ q包含每行git stdout的字符串数组。“只有当git生成多行输出时。如果git只输出一行到stdout,那么$ q将包含一个单一的字符串,而不是一个数组(我在我的回答中提到的东西)。 – 2013-04-28 19:34:31

+0

从OPs git commit commit(在我的机器上尝试它)返回多行。 – 2013-04-28 21:20:06

+1

我不使用该工具,因此我无法对此发表评论。但是我只想指出,这个特定的答案不能笼统地用于捕获命令行工具输出的所有情况。 – 2013-04-28 21:35:23

3

只是注意的是,-notcontains运营商并不意味着“字符串不包含子串”。这意味着“集合/数组不包含项目”。如果“git的承诺”命令返回一个字符串,你可以尝试这样的事:

if (-not $q.Contains("nothing to commit")) 

即使用包含字符串对象,并返回$真正的方法如果字符串包含一个子。

比尔

+0

'$ q'包含一个字符串数组(从Git的标准输出的所有行)......所以'$ q.Contains(“没有犯”)'将无法工作,'$ q [1] .Contains(“...”)'然而。 – 2013-04-28 00:03:15

+0

我已经注意到,当我说“如果'git commit'命令返回单个字符串”。 “ – 2013-04-28 00:14:12

相关问题