How to check if a string has spaces in Bash shell


Question

Say a string might be like "a b '' c '' d". How can I check that there is single/double quote and space contained in the string?

1
28
6/6/2019 6:03:48 PM

Accepted Answer

case "$var" in  
     *\ * )
           echo "match"
          ;;
       *)
           echo "no match"
           ;;
esac
26
9/24/2009 8:47:23 PM

You can use regular expressions in bash:

string="a b '' c '' d"
if [[ "$string" =~ \ |\' ]]    #  slightly more readable: if [[ "$string" =~ ( |\') ]]
then
   echo "Matches"
else
   echo "No matches"
fi

Edit:

For reasons obvious above, it's better to put the regex in a variable:

pattern=" |'"
if [[ $string =~ $pattern ]]

And quotes aren't necessary inside double square brackets. They can't be used on the right or the regex is changed to a literal string.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon