Strangeness in shell

David Elliott dce at Solbourne.COM
Tue Jul 25 01:39:11 AEST 1989


In article <9700009 at osiris.cso.uiuc.edu> funk at osiris.cso.uiuc.edu writes:
>>pjh at mcc.UUCP writes:
>>>	x='*z'
>>>	echo ${x}
>>>produces
>>>	*z
>>>but 
>>>	x='* z'
>>>	echo ${x}
>>>produces
>>>	(a list of all the files in the current directory) z
> Ummm... I had always learned (obviously flawed) that the single quotes 
>prevented expansion of ANYTHING....
>Even if this is not the case, why does it behave differently in the two cases?
>If you have no files ending in  z  , then why does it not return a null 
>string for the '*z' version ?   What is its algoithm for determining when it is going to be literal and when it is going to expand???

Don't confuse yourself.

The assignment x='anything' assigns the word to x *without* the single
quotes.  The single quotes do prevent all expansion, just as if each
character were preceded by a \ (the exception is in csh, in which a
single-quoted ! must still be escaped to prevent history expansion).

When you execute

	echo ${x}

the shell expands the value of the variable x, doing all processing that
occurs after variable substitution, which includes filename expansion.

If the statement were instead (and I wish people would learn to use
this, since it's the correct thing to do)

	echo "${x}"

the shell would expand the variable, but leave its contents alone, because
of the double quotes.

Now, as to why

	echo * z

expands the * and

	echo *z

doesn't, it's simply because sh is defined that way.  If it can't expand
the name, it leaves it alone.  You can do the same thing in csh by
setting "nonomatch" (and you thought this was an admonishment to a
naughty child ;-).

-- 
David Elliott		dce at Solbourne.COM
			...!{boulder,nbires,sun}!stan!dce



More information about the Comp.unix.questions mailing list