Introduction
You use regex inside [[ ]] with =~ to check if a string matches a pattern easily in bash scripts.
[[ string =~ regex_pattern ]]
[[ "hello123" =~ [a-z]+[0-9]+ ]]
[[ "$input" =~ ^[0-9]+$ ]]
[[ "file.txt" =~ \.txt$ ]]#!/bin/bash read -p "Enter a word: " word if [[ $word =~ ^[a-zA-Z]+$ ]]; then echo "Only letters detected." else echo "Contains other characters." fi
[[ "hello123" =~ [a-z]+[0-9]+ ]] check in a bash script?[a-z]+[0-9]+ means one or more lowercase letters followed by one or more digits.var matches regex ^[0-9]+$ in bash?[[ $var =~ ^[0-9]+$ ]] without quotes around regex, which is correct syntax.text="abc123" if [[ $text =~ ^[a-z]+[0-9]+$ ]]; then echo "Match" else echo "No match" fi
^[a-z]+[0-9]+$ means the string must start with one or more lowercase letters and end with one or more digits, with nothing else.input="2023-04-01"
if [[ "$input" =~ "^[0-9]{4}-[0-9]{2}-[0-9]{2}$" ]]; then
echo "Valid date"
else
echo "Invalid date"
fifilename ends with either ".jpg" or ".png" using regex in bash. Which condition correctly tests this?\.(jpg|png)$ matches a dot followed by 'jpg' or 'png' at the end of the string.Pass the test and this pattern moves unknown