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:

# is this a number?

if [ $# -eq 0 ] ; then
   echo Parameter is needed.

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

echo "Match: $BASH_REMATCH"

The running results are:

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

!1065 $ sh 123sdf line 8: BASH_REMATCH: no value

Share this post

Post Comment