Regular expressions in Bash 3

Since version 3 which released in 2004, Bash acquired a regular expression operator “=~”, but I never noticed it, probably because grep sed or other commands works alternatively well. The regular expression is the same as egrep,  you can find more details from man egrep.

In addition to doing simple matching, bash regular expressions support sub-patterns for capturing parts of the match. The matches are assigned to an array variable BASH_REMATCH. The entire match is assigned to BASH_REMATCH[0], the first sub-pattern is assigned to BASH_REMATCH[1], and going forward.

Below is an example:

#!/bin/bash
# is this a number?

number=$1
if [ $# -eq 0 ] ; then
   echo Parameter is needed.
   exit
fi

[[ "$number" =~ '\<[0-9]+\>' ]] && echo 'It is a number' || echo Sorry: ${BASH_REMATCH:?"no value"}

echo "Match: $BASH_REMATCH"

The running results are:

!1064 $ sh test.sh 3123
It is a number
Match: 3123

!1065 $ sh test.sh 123sdf
test.sh: line 8: BASH_REMATCH: no value
Share Button

Leave a comment

Your email address will not be published. Required fields are marked *