Operating System - HP-UX
1757924 Members
2527 Online
108866 Solutions
New Discussion

ksh: check if a shell variable contains spaces or is empty (maybe with case regexp)

 
support_billa
Valued Contributor

ksh: check if a shell variable contains spaces or is empty (maybe with case regexp)

hello,

 

i have to check, if  a shell variable contains only space(s) or is empty.

 

i tried to change the "case" regexp of this example :

 

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

 

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

 

so i made tests with "grep" and the "regexp"

string=""        # Return-Code: 0
echo "${string}" | grep "^[[:space:]]*[[:space:]]*$"
echo $?

string="   "     # Return-Code: 0
echo "${string}" | grep "^[[:space:]]*[[:space:]]*$"
echo $?

string=" test "  # Return-Code: 1
echo "${string}" | grep "^[[:space:]]*[[:space:]]*$"
echo $?

 

here is my version, but it doesn't work, also i don't know the syntax (... til)

case "${string}" in
  (^[[:space:]]*[[:space:]]*$)  echo "string contains space(s)"
		   ;;
  ("")             echo "string is empty"
		   ;;
  (*)              echo "string is not blank"
	          ;;
esac

 

regards

1 REPLY 1
Dennis Handly
Acclaimed Contributor

Re: ksh: check if a shell variable contains spaces or is empty (maybe with case regexp)

case and [[ = ]] do pattern matching, not regex.

So you would need to do sed, grep or awk.

 

I suppose you could use "typeset -L" to strip leading spaces and if the result matches " *", (space star), you have what you wanted.