Home > Software engineering >  Bash how to check if string contains '*'?
Bash how to check if string contains '*'?

Time:10-12

Bash how to check whether a string in bash contains *. Since * is a special character?

CodePudding user response:

You can use grep "\*"

As * is a special character it is then necessary to use the escape character \.

CodePudding user response:

if [[ $string == *"*"* ]]; then echo "string contains asterisk"; fi

Within double braces, the == operator does pattern matching. Quoted parts of a pattern are handled as literal strings.

With a regex, * is not special inside a bracket expression, or when quoted:

if [[ $string =~ [*] ]]; then echo "string contains asterisk"; fi
if [[ $string =~ "*" ]]; then echo "string contains asterisk"; fi
  • Related