bash – how to use regex in if condition

Bash built in double square brackets can be used for regex match in if condition. This can be pretty powerful and can be used in writing complex regex tests. Here are some examples.
bash-regex

Bash regex match

Here is a simple example to check if a url begins with /foo after the host part. Default match is case sensitive.

#!/bin/bash
URL=http://somedomain.com/foo/bar
if [[ $URL =~ ^http://somedomain.com/foo.*$ ]]; then
  echo "matched"
fi
if [[ $URL =~ ^http://somedomain.com/foo ]]; then
  echo "matched again"
fi
matched
matched again
Env: GNU bash, version 4.3.11

Bash regex match – case insensitive

To do case insensitive match set nocasematch using

shopt -s nocasematch

To unset nocasematch

shopt -u nocasematch

Here is sample code with case insensitive regex match

#!/bin/bash
shopt -s nocasematch
URL=http://SOMEDOMAIN.COM/foo/bar
if [[ $URL =~ ^http://somedomain.com/foo.*$ ]]; then
  echo "matched"
fi
matched
Env: GNU bash, version 4.3.11

Bash regex match – capture matched pattern

Print the matched content using ${BASH_REMATCH[n]}

#!/bin/bash
URL=http://somedomain.com/foo/bar
if [[ $URL =~ ^http://somedomain.com(/foo.*)$ ]]; then
  echo "matched"
  echo "full match: ${BASH_REMATCH[0]}"
  echo "first match: ${BASH_REMATCH[1]}"
fi
matched
full match: http://somedomain.com/foo/bar
first match: /foo/bar
Env: GNU bash, version 4.3.11

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments