0
0
Bash Scriptingscripting~5 mins

Regex in [[ ]] with =~ in Bash Scripting - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
AIf $var equals 'abc'
BIf $var starts with 'abc'
CIf $var ends with 'abc'
DIf $var contains 'abc' anywhere
What is stored in BASH_REMATCH[1] after a successful [[ $var =~ (pattern) ]] match?
AThe variable name
BThe full matched string
CThe first captured group
DThe regex pattern
Which is correct to check if $var contains only letters using regex in [[ ]]?
A[[ $var =~ "^[a-zA-Z]+$" ]]
B[[ $var =~ '[a-zA-Z]+' ]]
C[[ $var == ^[a-zA-Z]+$ ]]
D[[ $var =~ ^[a-zA-Z]+$ ]]
What does [[ $var =~ [0-9]{3} ]] return if $var='abc123def'?
ATrue, because '123' matches three digits
BFalse, because $var is not only digits
CError, regex is invalid
DFalse, because regex must be quoted
Why avoid quoting the regex in [[ $var =~ regex ]]?
AQuoting disables regex matching and treats it as a string
BQuoting makes the script run faster
CQuoting is required for special characters
DQuoting changes the variable value
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.