简体   繁体   中英

The equal tilde operator is not working in bash 4

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM