2

I'm following the bash manual and regex guide to do my script, but it doesn't work. The script always accepts all strings or numbers and doesn't follow the format.

This is a valid input: feat: RQ01_HelloWorld. ty

#!/usr/bin/env bash --posix
MSG="$1" 
FEAT=/feat:[[:space:]]RQ[[:digit:]]+_[[:alpha:]]+/
if [[ $MSG=~$FEAT ]]
    then
    echo "yeah"
else
    echo "is wrong"
    exit 1
fi
J.schmidt
  • 721
  • 5
  • 27
xra
  • 21
  • 4
  • 5
    You need spaces around the operator. – tripleee Feb 01 '19 at 15:03
  • 3
    The `/` aren't needed to surround the regular expression. – chepner Feb 01 '19 at 15:06
  • If you use `env` in the shebang line, you can't supply more parameters (such as `--posix`), you have to use `set -o posix` on a separate line instead. See [this Q&A](https://stackoverflow.com/questions/4303128/how-to-use-multiple-arguments-for-awk-with-a-shebang-i-e). I would have expected POSIX mode to not allow `=~` anyway, but it looks like it does after all. – Benjamin W. Feb 01 '19 at 15:23
  • POSIX reserves `[[` for implementation-specific purposes. It's behavior is unspecified, which means a shell can use it as it likes without being non-conforming. – chepner Feb 01 '19 at 15:39

1 Answers1

4

There are two problems:

1) Unlike in Perl or awk, where the regular expression is contained inside /.../ as part of the matching operation, bash does not use them like this. The / are considered part of the regular expression itself.

2) You need whitespace around the =~ operator so that [[ sees 3 distinct arguments, rather than a single non-empty string which [[ considers true.


FEAT="feat:[[:space:]]RQ[[:digit:]]+_[[:alpha:]]+"

if [[ $MSG =~ $FEAT ]]
chepner
  • 497,756
  • 71
  • 530
  • 681
  • i did that and work in regextester but when i run in bash it reject all, i'm using the same words in regextester and bash, maybe you know what happend? – xra Feb 01 '19 at 16:01
  • Does `$MSG` actually have the value you think it does? What happens if you add `[[ $MSG = "RQ01_HelloWorld" ]] || echo "error"` to your script and run it with `RQ01_HelloWorld` as the argument? – chepner Feb 01 '19 at 16:41