*BSD News Article 24595


Return to BSD News archive

Path: sserve!newshost.anu.edu.au!munnari.oz.au!news.Hawaii.Edu!ames!agate!howland.reston.ans.net!xlink.net!fauern!rrze.uni-erlangen.de!late.e-technik.uni-erlangen.de!eilts
From: eilts@late.e-technik.uni-erlangen.de (Hinrich Eilts)
Newsgroups: comp.unix.bsd
Subject: Re: test if file exists in script
Date: Tue, 30 Nov 1993 15:48:30 GMT
Organization: LATE, Uni-Erlangen, Germany
Message-ID: <2dfq0eEo4d@uni-erlangen.de>
References: <2deuhi$7lh@usenet.INS.CWRU.Edu>
NNTP-Posting-Host: late4.e-technik.uni-erlangen.de
Lines: 41

bx970@cleveland.Freenet.Edu (Donna A. Lilly) writes:

>What is the best way to test in a shell script (e.g. c shell or t shell if
>possible) whether a filename already exists?  Given a variable file, I
>could use:

>% if (`find . -name '$file' -print | wc -c` != 0) then
>    .....

>But I know there is a much better way.  I also didn't have much success
>with use of 

>% if (`test -s $file`) then

>also I tried the above without the backquotes, still didn't get any result
>from the test command...

It's a tricky problem, because tests in the above manner fails if
another process create the file between your test and the usage in this
process.
Try (in C-Shell notation):

set noclobber
cat "HELLO" > $file
echo $?

If $file not already exists, it will be created,
if it exists, you get an error and $? is != 0.

In sh:

#!/bin/sh
file=ttt
/bin/csh -c "set noclobber; echo $$ > $file"
echo $?

(If one know a direct way in sh, please mail it to me).
-- 
              Bye                                 | G i b   D O S |
                   Hinrich Eilts                  | k  e  i  n  e |
  (e-mail: eilts@late.e-technik.uni-erlangen.de)  | C h a n c e ! |