0
0
Bash Scriptingscripting~5 mins

Regex in [[ ]] with =~ in Bash Scripting

Choose your learning style9 modes available
Introduction
You use regex inside [[ ]] with =~ to check if a string matches a pattern easily in bash scripts.
Checking if a user input contains only numbers.
Finding if a filename ends with .txt before processing it.
Validating if an email address looks correct in a script.
Detecting if a log line contains a specific error code.
Syntax
Bash Scripting
[[ string =~ regex_pattern ]]
The regex pattern is written without quotes inside [[ ]].
If the string matches the pattern, the condition is true.
Examples
Checks if 'hello123' has letters followed by numbers.
Bash Scripting
[[ "hello123" =~ [a-z]+[0-9]+ ]]
Checks if the variable input contains only digits.
Bash Scripting
[[ "$input" =~ ^[0-9]+$ ]]
Checks if the string ends with '.txt'.
Bash Scripting
[[ "file.txt" =~ \.txt$ ]]
Sample Program
This script asks for a word and checks if it has only letters using regex inside [[ ]] with =~.
Bash Scripting
#!/bin/bash

read -p "Enter a word: " word

if [[ $word =~ ^[a-zA-Z]+$ ]]; then
  echo "Only letters detected."
else
  echo "Contains other characters."
fi
OutputSuccess
Important Notes
Do not quote the regex pattern inside [[ ]] when using =~, or it won't work as expected.
Regex matching with =~ is case sensitive by default.
You can use parentheses in regex for grouping, but remember to escape special characters if needed.
Summary
Use [[ string =~ regex ]] to test patterns in bash scripts.
The condition is true if the string matches the regex.
Do not put quotes around the regex pattern inside [[ ]].