Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The equal tilde operator is not working in bash 4

Tags:

regex

bash

bash4

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?

like image 987
Ricardo Braña Avatar asked Jan 06 '23 23:01

Ricardo Braña


1 Answers

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.

like image 66
Tom Fenech Avatar answered Jan 21 '23 06:01

Tom Fenech