How to check if a string has spaces in Bash shell

Solution 1:

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.

Solution 2:

case "$var" in  
     *\ * )
           echo "match"
          ;;
       *)
           echo "no match"
           ;;
esac

Solution 3:

You could do this, without the need for any backslashes or external commands:

# string matching

if [[ $string = *" "* ]]; then
  echo "string contains one or more spaces"
else
  echo "string doesn't contain spaces"
fi

# regex matching

re="[[:space:]]+"
if [[ $string =~ $re ]]; then
  echo "string contains one or more spaces"
else
  echo "string doesn't contain spaces"
fi

Based on this benchmark, the string match is much faster than the regex one.


Related:

  • How to check if a string contains a substring in Bash

Solution 4:

[[ "$str" = "${str%[[:space:]]*}" ]] && echo "no spaces" || echo "has spaces"