How to check if a string has spaces in Bash shell

Viewed 76585

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?

10 Answers

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:

What about this:

[[ $var == ${var//[ \"]/_} ]] && echo "quotes or spaces not found"

or if you like this:

if [[ $var == ${var//[ \"]/_} ]] ; then  
   echo "quotes or spaces not found" 
else
   echo "found quotes or spaces"
fi

Explanation: I'm evaluating a comparison between the variable ${var} and the variable ${var} itself after a on-the-fly non-destructive string substitution of all the quotes and spaces with an underscore.

Examples:

${var// /_}  # Substitute all spaces with underscores

The following code substitute all characters between the squared brackets (space and quotes) with an underscore. Note that quotes has to be protected with backslash:

${var//[ \"]/_}  
Related