The equal tilde operator is not working in bash 4
Asked Answered
M

2

5

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?

Misdoing answered 2/6, 2016 at 18:26 Comment(0)
C
8

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.

Crapulous answered 2/6, 2016 at 18:35 Comment(0)
I
1

In this case, where you just want to make sure that your parameter starts with tar, you don't need regular expression matching, simple pattern matching works as well:

e='tar xfz'
[[ $e == tar* ]] && echo 0 || echo 1
Impassion answered 7/6, 2016 at 18:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.