Jason
Jason

Reputation: 2492

Executing git-hooks on windows errors out

So,

I have written a simple git-hooks for pre-push which works just fine on Linux or Mac, but doesn't work on Windows.

Script: Tries to match the commit message with a regular expression, and should return 0 if matches or else exit.

Based on the articles I read, they say that the hook should just work.

Command:

if [[ "$message" =~ "$regular_expression" ]]; 

Error:

.git/hooks/pre-push: line 6: conditional binary operator expected
.git/hooks/pre-push: line 6: syntax error near `=~'
.git/hooks/pre-push: line 6: `  if [[ "$message" =~ "$regular_expression" ]]; then'

So apparently it seems to be failing on "[[" and "]]".

Now I have also tried removing the double brackets and keep only one.

Command:

if [ "$message" =~ "$regular_expression" ];

Error:

.git/hooks/pre-push: line 6: [: =~: binary operator expected
This message is flawed: TRY-1 Sample

Does anybody know how to solve this issue ?

Upvotes: 1

Views: 1127

Answers (1)

patthoyts
patthoyts

Reputation: 33193

The =~ construct in bash conditional expressions is not supported in the version of bash shipped with Git for Windows. It looks like the =~ operator was introduced in bash 3.0 but while Git for Windows is using bash 3.1 it seems to be missing this operator.

Possibly $(echo $message | grep "$regexp") will work as a substitute. eg:

$ bash -c '[[ "hello" =~ "^h" ]]'
bash: -c: line 0: conditional binary operator expected
bash: -c: line 0: syntax error near `=~'
bash: -c: line 0: `[[ "hello" =~ "^h" ]]'

$ bash -c '[ $(echo hello | grep "^h") ] && echo matched || echo nomatch'
matched

Update

Here is an example script that works to match something similar using the Git for Windows bash:

#!/bin/bash
#
# grep returns 0 on matching something, 1 whn it fails to match
msg='TEST-111 Sample'
re='([A-Z]{2,8}-[0-9]{1,4}[[:space:]])+[A-Za-z0-9]+[[:space:]]*[A-Za-z0-9]+$'
rx='^([A-Z]{2,8}-[0-9]{1,4})[[:space:]][[:alnum:]]+$'

echo $msg | grep -qE "$rx"
[ $? = 0 ] && echo matched || echo nomatch

This script returns matched for the sample phrase using the second regular expression. Its not really clear what the original expression is attempting to match up -- looks like multiple words so I'm not sure why you don't just match .*$. However, this shows a way to try out the regexp. Note: we are using extended regular expressions ([[:space:]]) so we have to use grep -E. Also we have to take some care about quoting as $ is being used in the regexp.

Upvotes: 2

Related Questions