Bash how to check whether a string in bash contains *. Since * is a special character?
            Asked
            
        
        
            Active
            
        
            Viewed 1,274 times
        
    0
            
            
        
        user7858768
        
- 838
 - 7
 - 22
 
- 
                    1escape it? after escaping it becomes exactly like any other characters, and checking it is just like checking if the string contains any other characters – phuclv Oct 12 '22 at 02:01
 
2 Answers
1
            
            
        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
        glenn jackman
        
- 238,783
 - 38
 - 220
 - 352
 
0
            
            
        You can use grep "\*" filename if you need to check if a string within a file contains a "*".
As * is a special character it is then necessary to use the escape character \.
        Olivier
        
- 1
 - 1
 
- 
                    no need to do that. Just `grep -F '*'`. But that's very expensive if the string is already in a variable – phuclv Oct 12 '22 at 16:11