Skip to content

Instantly share code, notes, and snippets.

@caruccio
Last active September 8, 2024 09:31
Show Gist options
  • Save caruccio/0b08ba0667ea2e171895412dc5c14a36 to your computer and use it in GitHub Desktop.
Save caruccio/0b08ba0667ea2e171895412dc5c14a36 to your computer and use it in GitHub Desktop.
Bash regex conditionals

In bash you can use [[ pattern =~ regex ]] to match on a conditional:

if [[ "hello world" =~ ^hell ]]; then
  echo Match
else
  echo No match
fi

The syntax is simple: [[ INPUT =~ REGEX ]].

Grouping match (REGEX)can be found in the array variable BASH_REMATCH:

URL=https://example.com

if [[ "$URL" =~ ^https?://([^/]+) ]]; then
  FOUND_DOMAIN=${BASH_REMATCH[1]}
  echo "Domain: $FOUND_DOMAIN"
else
  echo "Invalid URL"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment