2013-04-27 35 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