Subject: Re: string processing (was: text processing tool)
To: Lubos Vrbka <shnek@chemi.muni.cz>
From: Giorgos Keramidas <keramida@ceid.upatras.gr>
List: netbsd-help
Date: 03/13/2003 21:10:39
On Thu, 13 Mar 2003, Lubos Vrbka wrote:
> 
> one more question - if i read empty string into a variable in a
> script (/bin/ksh) (i.e. user just hits enter) and i want to test
> the variable, i always get an error message (the same applies to
> space and probably other white characters)
> 
> read variable
> if [ $variable = "abc" ]
> then
>    ...
> fi

Do what the shell substitution is supposed to do in your mind.  The
resulting command, when $variable contains only whitespace would be:

	if [    = "abc" ] ...

This isn't quite right.  You should *always* quote variables that are
used in test(1) expressions:

	if [ "$variable" = "abc" ]; then

when $variable contains just 2 spaces, the above will expand to:

	if [ "  " = "abc" ]; then

which works fine.

If you're interested in whitespace-only values, you can even use the
'case' builtin of sh(1):

	case "$variable" in
	[ ^I]*)
		# empty of whitespace-only value
		;;
	*)
		# everything else
		;;
	esac

> produces
> [: abc: unexpected operator
> 
> if [ $variable = "" ]
> or
> if [ $variable = " " ]
> works fine...  so how do i tell the system that empty string (or 
> space-filled string) is ok? man test doesn't tell me anything :o(

Checking for an empty string is better written as:

	if [ X"$variable" = X"" ]; then

This is a pretty idiomatic way of spelling this particular test in
shell scripts, and I've seen it in dozens of places.  It even works
with test(1) and [ implementations that really *require* the operands
of the '=' operator to be non-empty strings.

- Giorgos