You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Zsh中Source Bash脚本时BASH_REMATCH[1]为何返回空值?

Why does 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_REMATCH array, where BASH_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]}. The BASH_REMATCH array exists in Zsh as a compatibility feature, but it’s not automatically populated unless you explicitly enable the bashrematch option.

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):
    setopt bashrematch
    
    This tells Zsh to populate BASH_REMATCH just like Bash does, so your original code will work as-is when sourced in Zsh.

内容的提问来源于stack exchange,提问作者Sebastian Nemeth

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 15:47:29