Bob van Luijt
Bob van Luijt

Reputation: 7598

How to make a bash script fail based on grep regex?

I have the following bash script.

The problem I try to solve is really easy. When a commit in Git no starts with gh-1234 ... it should fail.

What is wrong with this bash script?

commit_regex='(gh-[0-9]+|merge)'

error_msg="Aborting commit. Your commit message is missing either a Github Issue ('gh-1111') or 'Merge'."

if ! grep -q "$commit_regex" <<< "$1"; then
    echo "$error_msg" >&2
    exit 1
fi

Upvotes: 0

Views: 197

Answers (2)

Rambler
Rambler

Reputation: 5490

Also another way to achieve the same without grep :

if [[ $git_message=~ $commit_regex ]] 
then
    echo "$error_msg"
    exit 1;
fi

Also : If the commit it "gh-1234" is mandated to be at the start of the message , you should add ^ in your regex.

Upvotes: 0

Chem-man17
Chem-man17

Reputation: 1770

As mentioned in the comments, you need to do grep -E "$commit_regex"

From the man grep page-

-E, --extended- Interpret PATTERN as an extended regular expression (ERE, see below). (-E is specified by POSIX.)

That should solve your problem since it forces grep to expand the variable.

Upvotes: 1

Related Questions