Recall & Review
beginner
What does the operator =~ do inside [[ ]] in bash?
The =~ operator tests if the string on the left matches the regular expression on the right inside [[ ]]. It returns true if it matches, false otherwise.
Click to reveal answer
beginner
How do you write a regex match to check if a variable contains only digits using [[ ]] and =~?
Use: [[ $var =~ ^[0-9]+$ ]] which means the variable contains one or more digits from start (^) to end ($).
Click to reveal answer
intermediate
What happens if you put the regex in quotes when using =~ inside [[ ]]?
If the regex is quoted, it is treated as a fixed string, not a regex. This usually breaks the pattern matching. So, do NOT quote the regex.
Click to reveal answer
intermediate
How can you access the part of the string matched by the regex after using =~?
Bash stores the matched groups in the array variable BASH_REMATCH. BASH_REMATCH[0] is the full match, BASH_REMATCH[1] the first group, and so on.
Click to reveal answer
beginner
Why use [[ ]] with =~ instead of [ ] with grep or test?
[[ ]] with =~ is faster and simpler for regex matching inside bash scripts. It avoids spawning external commands like grep, making scripts more efficient.
Click to reveal answer
In bash, what does [[ $var =~ ^abc ]] check?
✗ Incorrect
The regex ^abc means the string starts with 'abc'.
What is stored in BASH_REMATCH[1] after a successful [[ $var =~ (pattern) ]] match?
✗ Incorrect
BASH_REMATCH[1] holds the first captured group from the regex.
Which is correct to check if $var contains only letters using regex in [[ ]]?
✗ Incorrect
Regex should NOT be quoted inside [[ ]] with =~ to work properly.
What does [[ $var =~ [0-9]{3} ]] return if $var='abc123def'?
✗ Incorrect
The regex matches any three digits anywhere in the string.
Why avoid quoting the regex in [[ $var =~ regex ]]?
✗ Incorrect
Quoting the regex disables pattern matching and treats it as a plain string.
Explain how to use regex matching inside [[ ]] with =~ in bash scripts.
Think about how bash tests patterns without external tools.
You got /4 concepts.
Describe common mistakes when using =~ with regex in bash and how to avoid them.
Focus on syntax and quoting rules.
You got /4 concepts.