Testing a string containing only spaces (tabs, or " ")?

7,434

Solution 1

No need for bash specific code:

case $string in
  (*[![:blank:]]*) echo "string is not blank";;
  ("") echo "string is empty";;
  (*) echo "string is blank"
esac

Solution 2

From man bash:

An additional binary operator, =~, is available, with the same precedence as == and !=. When it is used, the string to the right of the operator is considered an extended regular expression and matched accordingly (as in regex(3)).

So the regular expression matching operator should be =~:

if [[ "$stringZ" =~ ^[[:blank:]][[:blank:]]*$ ]];then
  echo  string is  blank
else
  echo string is not blank
fi

You can reduce the verbosity of the regular expression by using + quantifier (meaning previous entity 1 or more times):

if [[ "$stringZ" =~ ^[[:blank:]]+$ ]]; then
Share:
7,434

Related videos on Youtube

Ezequiel
Author by

Ezequiel

Updated on September 18, 2022

Comments

  • Ezequiel
    Ezequiel almost 2 years

    My code below doesn't work:

    stringZ="    "
    
    if [[ "$stringZ" == ^[[:blank:]][[:blank:]]*$ ]];then
      echo  string is  blank
    else
      echo string is not blank
    fi 
    

    Result:

    string is not blank   # wrong
    

    How can I test this?

    • Ezequiel
      Ezequiel about 9 years
      I think I asked this before in 2013 :-)