How to Check if String Has Spaces in Bash (With Example)


Often you may want to use Bash to check if a string has spaces or not.

You can use the following syntax to do so:

if [[ $my_string =~ [[:space:]]+ ]]; then
  echo "String contains at least one space"
else
  echo "String does not contain spaces"
fi

This particular example will check if the string variable named my_string contains any spaces and return one of the following as a result:

  • String contains at least one space
  • String does not contain spaces

Feel free to change the text returned by the echo statement to anything that you would like.

The following example shows how to use this syntax in practice.

Example: How to Check if String Has Spaces in Bash

Suppose that we create the following string variable named my_string in Bash:

  • Dallas Mavericks

We can use the following syntax to check if this string has spaces:

my_string="Dallas Mavericks"

if [[ $my_string =~ [[:space:]]+ ]]; then
  echo "String contains at least one space"
else
  echo "String does not contain spaces"
fi

The following screenshot shows how to use this syntax in practice:

Bash check if string contains spaces

The output returns “String contains at least one space” since the string variable does indeed contain at least one space.

Suppose instead that we create the following string variable named my_string in Bash:

  • DallasMavericks

We can use the following syntax to check if this string has spaces:

my_string="DallasMavericks"

if [[ $my_string =~ [[:space:]]+ ]]; then
  echo "String contains at least one space"
else
  echo "String does not contain spaces"
fi

The following screenshot shows how to use this syntax in practice:

The output returns “String does not contain spaces” since the string variable indeed does not contain any spaces.

Feel free to use similar syntax to check if your own variable contains spaces or not.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

Bash: How to Replace Text in String
Bash: How to Replace Space with Underscore
Bash: How to Replace Special Characters in String
Bash: How to Replace Multiple Characters in String

Leave a Reply