Sign up ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

This question already has an answer here:

My code below doesn't work:

stringZ="    "

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


string is not blank   # wrong

How can I test this?

share|improve this question

marked as duplicate by G-Man, Stephen Kitt, X Tian, Anthon, Flup Jun 22 at 13:00

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

I think I asked this before in 2013 :-) – munish Jun 23 at 5:36

2 Answers 2

up vote 7 down vote accepted

No need for bash specific code:

case $string in
  (*[^[:blank:]]*) echo "string is not blank";;
  ("") echo "string is empty";;
  (*) echo "string is blank"
share|improve this answer

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
  echo string is not blank

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

if [[ "$stringZ" =~ ^[[:blank:]]+$ ]]; then
share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.