In a server with bash version 3 I do this:
bash3$ e="tar xfz"; [[ "$e" =~ "^tar" ]] && echo 0 || echo 1
0
But when I execute the same command in bash version 4
bash4$ e="tar xfz"; [[ "$e" =~ "^tar" ]] && echo 0 || echo 1
1
I tried it in CentOS, Fedora and Ubuntu and got the same results. What is wrong?
Quoting the section on regular expressions from Greg's Wiki:
Before 3.2 it was safe to wrap your regex pattern in quotes but this has changed in 3.2. Since then, regex should always be unquoted.
This is the most compatible way of using =~
:
e='tar xfz'
re='^tar'
[[ $e =~ $re ]] && echo 0 || echo 1
This should work on both versions of bash.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With