C-Shell weirdness

Greg Woods woods at hao.UUCP
Wed Mar 26 07:01:57 AEST 1986


>    the statement:
> 
>            if ($arg == '-b') echo 'UNIX is fun'

   ...should in fact be:

	     if ("$arg" == "-b") echo 'UNIX is fun'

   This really is a feature, not a bug, and I actually have some shell
scripts that use it to test various kinds of access to files for various
reasons, such as the following trivial example:

foreach access (e r w x)
if (-$access "$file") echo $access access is permitted to $file
end

Moral of story: ALL strings used in if tests should be quoted. Double quotes
still permits variable substitution, single quotes inhibit it (believe it
or not, this IS actually documented in the csh(1) man page! :-)

> 2: Count of number of words in a variable (Or when is nothing something)
> 
> This:
> 
> set hosed = ''
> echo $#hosed
> 
> yields the result '1'

  But of course! The variable has one value: a null string. And, if you do

set hosed=( '' junk)

then what do you suppose $#hosed is? If you got 2, drink a potion of raise
level and read on! :-) If you do

set hosed
echo $#hosed

THEN you will get 0. The difference? A null string is different from no value
at all. This too has it's uses, such as when each word of a variable stands
for an attribute of the object represented by the variable, and a null string
means that attribute does not exist (i.e. a kludgy implentation of a
structure in a shell script. And yes, I'm masochistic; I actually have
real scripts that use this too :-)

> 3: Logical not operator
> 
> According to the csh man page the logical not operator "!" is available.

  Also according to the man page, any non-space character after ! invokes
the history mechanism. While it does not (and probably should) say this
explicitly in the documentation for the ! not operator, it follows
from this that what is needed is a space after the ! when using it as
a unary logical operator, e.g. 

> set lights_on = 1
> if (!$lights_on) echo 'nobody home'

set lights_on=1
if (! $lights_on) echo 'nobody home'

The best way to implement Boolean flags under csh is much simpler: the variable
exists or it doesn't. The construct $?var returns 1 if var is defined and 0
if it isn't, and is NOT an error if var is undefined. I.e. your above example
converts to:

set lights_on
if (! $?lights_on) echo 'nobody home'

Hope this helps.

--Greg



More information about the Comp.unix.wizards mailing list