-1

I was trying to use a bash script to validate some strings. No matter what I've tried, the script ends up matching every string provided as input and it's printing yes in the terminal. For example, ABCDCD should print itself and "yes", whereas SSSS should just print itself. However, both seem to be printing themselves and "yes".

#! /bin/bash

read str
echo $str
reg1="AB[CD]*"
if [ $str=~$reg1 ];then
echo "yes"
fi
  • 2
    `[ ]` (the `test` command) does not support regular expression comparisons; you need a bash conditional expression with `[[ ]]`. You also need spaces around the `=~` operator. See ["Difference between single and double square brackets in Bash"](https://stackoverflow.com/questions/13542832/difference-between-single-and-double-square-brackets-in-bash/31366734#31366734) and ["Why equal to operator does not work if it is not surrounded by space?"](https://stackoverflow.com/questions/4977367/why-equal-to-operator-does-not-work-if-it-is-not-surrounded-by-space) – Gordon Davisson Oct 03 '20 at 04:12
  • 2
    Also, I recommend using [shellcheck.net](https://www.shellcheck.net) to check for common mistakes like these. – Gordon Davisson Oct 03 '20 at 04:18

1 Answers1

0

-You should use [[ ]] instead [] for regex test, space between == or =~, recommend should not double quote the regex. I think it should be

#! /bin/bash

read str
echo $str
reg1="AB[CD]*"
if [[ "$str" =~ $reg1 ]];then
echo "yes"
fi
  • Note that with regex AB[CD]*, it will also echo yes with input like ABDXYZ, ABXYZ, ...It means third character can be C or D or anything. – stackoverflower Oct 03 '20 at 09:15