Bird
Raised Fist0
Bash Scriptingscripting~10 mins

Capture groups in Bash in Bash Scripting - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Capture groups in Bash
Input string
↓
Apply regex with capture groups
↓
Match found?
No→No capture groups
Yes↓
Extract groups into variables
↓
Use captured values
Bash applies a regex with capture groups to a string, checks for matches, and extracts matched parts into variables for use.
Execution Sample
Bash Scripting
text="Name: John, Age: 30"
if [[ $text =~ Name: ([A-Za-z]+), Age: ([0-9]+) ]]; then
  name=${BASH_REMATCH[1]}
  age=${BASH_REMATCH[2]}
fi
 echo "$name is $age years old"
Extracts name and age from a text string using capture groups in a regex.
Execution Table
StepActionRegex Match ResultBASH_REMATCH ContentVariables SetOutput
1Set text variable----
2Apply regex to textMatch found["Name: John, Age: 30", "John", "30"]--
3Extract name from BASH_REMATCH[1]--name=John-
4Extract age from BASH_REMATCH[2]--age=30-
5Print output---John is 30 years old
💡 Regex matched successfully, capture groups extracted, output printed.
Variable Tracker
VariableStartAfter Step 3After Step 4Final
text"Name: John, Age: 30""Name: John, Age: 30""Name: John, Age: 30""Name: John, Age: 30"
BASH_REMATCHempty["Name: John, Age: 30", "John", "30"]["Name: John, Age: 30", "John", "30"]["Name: John, Age: 30", "John", "30"]
nameemptyJohnJohnJohn
ageemptyempty3030
Key Moments - 3 Insights
Why do we use double brackets [[ ]] for regex matching instead of single brackets [ ]?
Double brackets [[ ]] support regex matching with =~ operator in Bash, while single brackets [ ] do not. This is shown in Step 2 where regex matching happens.
What does BASH_REMATCH[0] contain compared to BASH_REMATCH[1] and [2]?
BASH_REMATCH[0] contains the full matched string, while BASH_REMATCH[1], [2], etc. contain the capture groups. See Step 2's BASH_REMATCH content.
What happens if the regex does not match the text?
The if condition fails, no variables are set from BASH_REMATCH, and no output is printed. This is the 'No' branch in the concept flow.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table at Step 2. What is the content of BASH_REMATCH?
A["Name: John, Age: 30", "John", "30"]
B["John", "30"]
C["Name: John, Age: 30"]
Dempty
💡 Hint
Check the 'BASH_REMATCH Content' column in Step 2 of the execution table.
At which step is the variable 'age' assigned a value?
AStep 2
BStep 3
CStep 4
DStep 5
💡 Hint
Look at the 'Variables Set' column in the execution table.
If the input text was 'Name: Alice, Age: 25', how would the variable 'name' change in the variable tracker?
AIt would remain empty
BIt would be set to 'Alice'
CIt would be set to 'John'
DIt would cause an error
💡 Hint
The variable 'name' is set from the first capture group, see variable_tracker and execution_table Step 3.
Concept Snapshot
Capture groups in Bash use [[ string =~ regex ]] to match.
Matched groups are stored in BASH_REMATCH array.
BASH_REMATCH[0] is full match; [1], [2], etc. are capture groups.
Use capture groups to extract parts of strings easily.
Always check if regex matched before using BASH_REMATCH.
Full Transcript
This visual trace shows how Bash uses capture groups in regex matching. First, a text string is set. Then, the regex with capture groups is applied using double brackets and the =~ operator. If the regex matches, Bash fills the BASH_REMATCH array with the full match and each capture group. We extract the desired parts from BASH_REMATCH[1], BASH_REMATCH[2], etc., and assign them to variables. Finally, we use these variables, for example, printing the extracted name and age. If the regex does not match, no variables are set and no output is printed. This step-by-step helps beginners see how capture groups work in Bash scripting.

Practice

(1/5)
1. What does the BASH_REMATCH array hold after a successful regex match in Bash?
easy
A. The full matched string at index 0 and captured groups from index 1 onwards
B. Only the captured groups without the full match
C. The regex pattern used for matching
D. The exit status of the last command

Solution

  1. Step 1: Understand BASH_REMATCH usage

    When using [[ string =~ regex ]], Bash stores the full matched text in BASH_REMATCH[0].
  2. Step 2: Identify captured groups storage

    Captured groups from parentheses in the regex are stored starting at BASH_REMATCH[1] onwards.
  3. Final Answer:

    The full matched string at index 0 and captured groups from index 1 onwards -> Option A
  4. Quick Check:

    BASH_REMATCH = full match + groups [OK]
Hint: Remember index 0 is full match, groups start at 1 [OK]
Common Mistakes:
  • Thinking BASH_REMATCH holds only groups
  • Confusing BASH_REMATCH with exit status
  • Expecting regex pattern in BASH_REMATCH
2. Which of the following is the correct syntax to test if a string matches a regex and capture groups in Bash?
easy
A. match $string $regex
B. if ($string =~ $regex); then
C. [[ $string =~ $regex ]]
D. test $string =~ $regex

Solution

  1. Step 1: Recall Bash regex match syntax

    Bash uses the conditional expression [[ string =~ regex ]] to test regex matches.
  2. Step 2: Identify correct syntax among options

    Only [[ $string =~ $regex ]] uses the correct Bash syntax with double brackets and the =~ operator.
  3. Final Answer:

    [[ $string =~ $regex ]] -> Option C
  4. Quick Check:

    Use [[ ]] with =~ for regex match [OK]
Hint: Use double brackets [[ ]] with =~ for regex matching [OK]
Common Mistakes:
  • Using single brackets [ ] which don't support =~
  • Using parentheses () like in other languages
  • Using commands like test or match incorrectly
3. What will be the output of this Bash script?
string="user:1234"
if [[ $string =~ ([a-z]+):([0-9]+) ]]; then
echo "Name=${BASH_REMATCH[1]}, ID=${BASH_REMATCH[2]}"
fi
medium
A. Name=user, ID=1234
B. Name=user:1234, ID=
C. Name=, ID=
D. Syntax error

Solution

  1. Step 1: Analyze regex and string

    The regex ([a-z]+):([0-9]+) matches letters before colon and digits after colon in the string "user:1234".
  2. Step 2: Check captured groups in BASH_REMATCH

    BASH_REMATCH[1] captures "user" and BASH_REMATCH[2] captures "1234".
  3. Final Answer:

    Name=user, ID=1234 -> Option A
  4. Quick Check:

    Captured groups print correct values [OK]
Hint: Captured groups appear in BASH_REMATCH starting at index 1 [OK]
Common Mistakes:
  • Expecting full string in BASH_REMATCH[1]
  • Forgetting to use double brackets [[ ]]
  • Misreading regex pattern
4. Identify the error in this Bash snippet:
string="abc123"
if [[$string =~ ([a-z]+)([0-9]+)]]; then
echo "${BASH_REMATCH[1]} and ${BASH_REMATCH[2]}"
fi
medium
A. Regex pattern is invalid
B. Missing spaces inside [[ and ]]
C. BASH_REMATCH is not set by =~ operator
D. Using single brackets instead of double brackets

Solution

  1. Step 1: Check syntax of conditional expression

    The conditional expression [[ ... ]] requires spaces after [[ and before ]]. The snippet misses spaces.
  2. Step 2: Confirm regex and BASH_REMATCH usage

    The regex is valid and BASH_REMATCH is set correctly when using =~ inside [[ ]].
  3. Final Answer:

    Missing spaces inside [[ and ]] -> Option B
  4. Quick Check:

    Spaces needed inside [[ and ]] [OK]
Hint: Always put spaces after [[ and before ]] [OK]
Common Mistakes:
  • Omitting spaces inside [[ ]]
  • Confusing single [ ] with [[ ]]
  • Assuming regex pattern is wrong
5. You want to extract the domain and path from a URL string in Bash using capture groups. Which regex and code snippet correctly captures domain and path?
url="https://example.com/path/to/page"
if [[ $url =~ https://([^/]+)(/.*) ]]; then
echo "Domain: ${BASH_REMATCH[1]}"
echo "Path: ${BASH_REMATCH[2]}"
fi
hard
A. Captures domain and path but misses https:// prefix
B. BASH_REMATCH does not support multiple groups
C. Fails because regex does not escape dots
D. Correctly captures domain as example.com and path as /path/to/page

Solution

  1. Step 1: Analyze regex pattern

    The regex https://([^/]+)(/.*) matches 'https://' literally, then captures domain (any chars except '/') and path (slash followed by anything).
  2. Step 2: Check BASH_REMATCH usage

    BASH_REMATCH[1] holds domain, BASH_REMATCH[2] holds path, correctly extracted from the URL.
  3. Final Answer:

    Correctly captures domain as example.com and path as /path/to/page -> Option D
  4. Quick Check:

    Regex groups extract domain and path correctly [OK]
Hint: Use ([^/]+) for domain and (/.*) for path [OK]
Common Mistakes:
  • Not escaping dots in regex (not needed inside character class)
  • Assuming BASH_REMATCH can't hold multiple groups
  • Missing literal https:// in regex
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard