Why do people use: if [ "x$FOO" = "x" ] .... ?

Rob Warnock rpw3 at redwood.UUCP
Wed Apr 17 19:57:59 AEST 1985


There is one case... uh, situation... in which the x$FOO construct (NO quotes!)
is useful, and that's when you are trying to allow partial matching. (But see
the caveat that follows.)

Suppose you are asking for confirmation and you want any of "y", "ye",
or "yes", or "yo" or anything else starting with "y" to mean "yes",
and anything starting with "n" to mean "no". (Yes, this is not good
human engineering, but gimme a break, for the example's sake!). Then
you would use:

	echo -n 'Do it? '	# echo 'Do it? \c' for System V
	read answer
	case X$answer in
	Xy*)	... yes ... ;;
	Xn*)	... no ... ;;
	*)	echo 'Please type yes or no"... ;;
	esac

Using "$answer" doesn't work unless you explicitly list ALL of the choices,
since "*" isn't expanded inside strings, so you have to do this:

	case "$answer" in
	"y"|"ye"|"yes"|"yep"|"yea"|"yeah"|"yo")	... yes ...;;
	"n"|"no"|"nope"|"nada"|"nah")		... no ...;;
	*)					echo 'I do not understand...' ;;
	esac

Be that as it may, I have started using the latter form myself, as the
X$answer form does not protect against (even accidental) typing of multiple
words in the answer. The "$answer" form does not blow up in this case,
and so is preferred (by fumble-fingers such as myself). I generally allow
only "y" and "yes" for YES and "n" and "no" for NO; I have found I get few
complaints from "nay"-sayers... ;-}


Rob Warnock
Systems Architecture Consultant

UUCP:	{ihnp4,ucbvax!dual}!fortune!redwood!rpw3
DDD:	(415)572-2607
USPS:	510 Trinidad Lane, Foster City, CA  94404



More information about the Comp.unix mailing list