Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String comparison not working in PowerShell function - what am I doing wrong?

I'm trying to make an alias of git commit which also logs the message into a separate text file. However, if git commit returns "nothing to commit (working directory clean)", it should NOT log anything to the separate file.

Here's my code. The git commit alias works; the output to file works. However, it logs the message no matter what gets returned out of 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

I'm using PowerShell 3.

like image 265
adrienne Avatar asked Apr 27 '13 23:04

adrienne


1 Answers

$q contains a string array of each line of Git's stdout. To use -notcontains you'll need to match the full string of a item in the array, for example:

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

If you want to test for a partial string match try the -match operator. (Note - it uses regular expressions and returns a the string that matched.)

$q -match "nothing to commit"

-match will work if the left operand is an array. So you could use this logic:

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

Yet another option is to use the -like/-notlike operators. These accept wildcards and do not use regular expressions. The array item that matches (or doesn't match) will be returned. So you could also use this logic:

if (-not ($q -like "nothing to commit*")) {
    "there was something to commit.."
}
like image 111
Andy Arismendi Avatar answered Sep 29 '22 09:09

Andy Arismendi