在Zsh中Source Bash脚本时BASH_REMATCH[1]为何返回空值?
BASH_REMATCH[1] return empty when sourcing a Bash regex script in Zsh? Let’s break down exactly why you’re seeing this confusing behavior:
1. The shebang is ignored when sourcing scripts
Your script starts with #!/usr/bin/env bash—this line tells the OS to use Bash to run the script when you execute it directly (like ./cutescript.sh). But when you use source (or .) to run the script, your current shell (Zsh, here) reads and executes every line itself. The shebang is completely ignored in this scenario, so Zsh doesn’t hand off execution to Bash at all.
2. Zsh handles regex matches differently than Bash
While Zsh supports the [[ $TEXT =~ $REGEX ]] syntax for regex matching, it doesn’t use BASH_REMATCH to store capture groups by default:
- In Bash, successful matches populate the
BASH_REMATCHarray, whereBASH_REMATCH[1]holds the first captured group. - In Zsh, the default variable for capture groups is
match—you’d access the first group with${match[1]}. TheBASH_REMATCHarray exists in Zsh as a compatibility feature, but it’s not automatically populated unless you explicitly enable thebashrematchoption.
That’s why your script reports "matched successfully" (Zsh does find the regex match) but BASH_REMATCH[1] is empty—Zsh just isn’t putting the captured text into that array by default.
Fixes to resolve this
Option 1: Run the script with Bash instead of sourcing it
Stick to executing the script directly with ./cutescript.sh or bash ./cutescript.sh—this uses the shebang to launch Bash, so all Bash-specific behavior (including BASH_REMATCH) works as expected.
Option 2: Adapt the script for Zsh compatibility
If you need to source the script in Zsh, you have two paths:
- Modify the script to use Zsh’s native match variable:
if [[ $TEXT =~ $REGEX ]]; then echo "Matched ${match[1]}" else echo "No match." fi - Enable Zsh’s Bash compatibility for regex matches by adding this line at the top of the script (right after the shebang):
This tells Zsh to populatesetopt bashrematchBASH_REMATCHjust like Bash does, so your original code will work as-is when sourced in Zsh.
内容的提问来源于stack exchange,提问作者Sebastian Nemeth

