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?

Benjamin W.
  • 46,058
  • 19
  • 106
  • 116

2 Answers2

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.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Tom Fenech
  • 72,334
  • 12
  • 107
  • 141
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
Benjamin W.
  • 46,058
  • 19
  • 106
  • 116