So I created myself a cute little bash script:
#!/usr/bin/env bash
TEXT="FOO BAR"
REGEX="FOO (.+)"
if [[ $TEXT =~ $REGEX ]]; then
echo "Matched ${BASH_REMATCH[1]}"
else
echo "No match."
fi
Pretty basic. If I run ./cutescript.sh
, then I get the result:
Matched BAR
But if I source the script, . ./cutescript.sh
. ./cutescript.sh
, then it still matches, but BASH_REMATCH[1
is empty.
Wat.
I'm on MacOS Catalina 10.15.7 (19H2), executing this in zsh
, but with the bash
shebang.
Can anyone explain this irregularity?
When you read the file with .
, it gets executed by whatever shell you're running - in this case, you said you're in zsh. The name of the BASH_REMATCH
array is, as the name implies, specific to bash
; if your shell is zsh, for example, then the matched text in this case would be found in $match[1]
instead. And I don't think ksh does true regex matching at all.
Now, armed with the knowledge that BASH_REMATCH
doesn't exist natively in zsh
, I did a little more digging:
This post is actually a duplicate. There's another question here that explains the solution: BASH_REMATCH doesn't capture
Setting options KSH_ARRAYS
BASH_REMATCH
allows zsh
to emulate bash
's regular expression features.
A simple way to make the above script compatible with zsh
is:
#!/usr/bin/env bash
# Ensures that BASH_REMATCH works if called in zsh.
setopt KSH_ARRAYS BASH_REMATCH
TEXT="FOO BAR"
REGEX="FOO (.+)"
if [[ $TEXT =~ $REGEX ]]; then
echo "Matched ${BASH_REMATCH[1]}"
else
echo "No match."
fi
unsetopt KSH_ARRAYS BASH_REMATCH
Also another related question: What is the zsh equivalent for $BASH_REMATCH[]?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.