peter@aucs.AcadiaU.ca (Peter Steele) (05/09/91)
I wrote a simple Cshell script the other day that looked something like this: set f=`ls` if $#f > 1 then ... endif In other words, I only wanted the if statement to be executed if there was more than one file in the directory. This did not work; it went ahead and did the body of the if statement even when there was only one file present. To file the problem, I added some brackets: if ($#f > 1) then ... Why are parentheses needed here? I know I've done other stuff that hasn't needed parentheses, e.g. if $status != 0 then ... What's the story? -- Peter Steele Postmaster peter.steele@acadiau.ca Tel: 902-542-2201 Software Analyst, Acadia University, Wolfville, NS Fax: 902-542-7224
jik@athena.mit.edu (Jonathan I. Kamens) (05/09/91)
The csh man page does not document the ability to have if statements without
parentheses around the boolean expression, and it is *not* something you
should rely on, because it is not supported and will break much of the time.
In the particular example you gave:
set f=`ls`
if $#f > 1 then
...
endif
breaks because the shell notices the '>' and assumes that it is redirection
rather than a numerical comparison. I suspect there's a file called "1" in
the directory in which you ran this shell script.
I should probably mention that parentheses aren't the only thing you can use
-- you can also use curly braces, which cause a csh if statment to function
much the same way the bourne shell's if statement functions. This:
foo
if ($status == 0) then
...
endif
is equivalent to this:
if { foo } then
...
endif
This is a useful feature whose documentation is unfortunately buried deep in
the man page for csh, and is only mentioned in passing -- "Also available in
expressions as primitive operands are command executions enclosed in `{' and
`}'..." Of course, it never explains what "command executions" are.
--
Jonathan Kamens USnail:
MIT Project Athena 11 Ashford Terrace
jik@Athena.MIT.EDU Allston, MA 02134
Office: 617-253-8085 Home: 617-782-0710