Home > Software engineering >  Finding whitespaces in string variable shell script
Finding whitespaces in string variable shell script

Time:04-01

I have a string variable which could have values like below.

my_string=" "
my_string="   "
my_string="name1"
my_string="name 2"

I have to identify if my_string has only spaces/whitespaces and exit the program when it has only whitespaces. If it has one or two spaces inbetween, it's a valid string.

How to check if the string has only whitespaces and exit the shell script based on that.

Thank you.

CodePudding user response:

Your question is somewhat unclear. However the following example should point you in the right direction.

#!/bin/sh

#my_string=""
my_string="     "
#my_string="   "
#my_string="name1"
#my_string="name 2"

case "$my_string" in
  "")             echo "string is empty";;
  *[![:space:]]*) echo "string does not contain only whitespace";;
  *)              echo "string contains only whitespace"; exit 1;;
esac

If you want to test only for spaces and tabs rather than all whitespace, you should use [:blank:] instead of [:space:].

CodePudding user response:

Since you are searching for a solution in POSIX shell, I would do something like this:

if [ "$(echo $my_string | tr -d ' ')" = '' ]
then
  echo The string is blank
fi
  • Related