Reputation: 694
Given two strings :-
a="hello h"
b=""
In bash version 4.2, their regex compare results in true
[[ "${a}" =~ "${b}" ]]
echo $? # 0
In bash version 3.2, the regex compare results in false
[[ "${a}" =~ "${b}" ]]
echo $? # 2
Edit : 1st result is run on linux os shipping with 4.2.46(2)-release bash, while 2nd result is run OS Mojave running 3.2.57(1)-release bash.
Upvotes: 0
Views: 117
Reputation: 180316
bash regex match behaving differently across bash versions
Evidently they do.
In bash version 3.2, the regex compare results in false
That's not quite correct. You indicate that the exit status is 2, which conveys that the pattern given is syntactically incorrect. That's a failure result, yes, and the status will be treated as false in boolean context, but it does not convey that the string does not match the pattern. Rather, it conveys that no regex match attempt was performed at all.
I'm not sure where to find a manual for Bash 3.2, which is pretty old, but it's not crazy that it rejects empty regexes. You should be able to work around that issue by handling the empty-regex case specially:
[[ -z "${b}" ]] || [[ "${a}" =~ "${b}" ]]
echo $?
Do note, however, that quoting the regex causes it to be treated as a plain string. If you want to test whether the plain string stored in variable b
appears as a substring of the one stored in a
, then you could also do so via a case
expression:
case $a in
*${b}*) echo "it matches" ;;
*) echo "it doesn't match" ;;
esac
Upvotes: 5