The "if ( -e filename )" blues...

Jonathan I. Kamens jik at cats.ucsc.edu
Tue Jun 18 08:12:14 AEST 1991


In article <1991Jun17.195519.12713 at murdoch.acc.Virginia.EDU>, eas at turing.acs.virginia.edu (Edward A. Schwab) writes:
|> Help!  I'm trying to run a simple csh shell file that sets $OUT.out to an
|> output filename and $PROG to a program name, will search for $OUT.out, and
|> delete it...  I'm trying to do an "if ( -e $OUT.out ) set x=$<", which will
|> wait for an ENTER before continuing with the program...  The only thing is
|> that the "if ( -e )" statement (that searches for the existance of the file)
|> runs if there is an actual $OUT.out file or not...

In order to realize why this is happening, you have to keep in mind exactly
what $< is.  In particular, it's a gross hack to do keyboard input using a
variable substitution.  *Variable substition* is the key here.  On a single
line "if" statement in C-shell input, variable substitution happens on the
entire line *before* the boolean of the "if" statement is checked.  Since the
$< hack is a variable substitution, the shell reads a line of input in order
to put a value in place of $< *before* it checks if the boolean is true.

The fix is simple.  Change your script to read:

if ( -e $OUT.out) then
	set x=$<
endif

In fact, a large portion of your script can be enclosed in that if statement. 
Rather than checking if $OUT.out exists before each line of the warning is
printed, you can do:

if ( -e $OUT.out ) then
	clear
	echo '******************************************************'
	echo 'You have a leftover '$OUT'.out file.  Since '$PROG''
	echo 'will end up choking on this leftover file,  I am going'
	echo 'to  delete  it  for  you.  If  you  do not  want me to'
	echo 'delete it, hit ^C, ENTER, and rename it to a different'
	echo '                      filename.'
	echo '******************************************************'
	echo ' '
	echo ' If you want it deleted, press ENTER now to continue.'
	set x=$<
	rm $OUT.out
endif

-- 
Jonathan Kamens					jik at CATS.UCSC.EDU



More information about the Comp.unix.questions mailing list