简体   繁体   中英

if else statement error checking

I am attempting to error check so that if the file is not an ordinary file it will echo File is not an ordinary file.

#!/bin/csh

echo Enter file name
set filename = $<

if(-f $filename)then

        if(-z $filename)then
        rm $filename    

        else
        clear
        echo $filename
        du -sh $filename
        stat -c %h $filename
        stat -c %U $filename
        date -r $filename

        endif
else
echo File is not an ordinary file
endif

when I run this with for example fake.txt it comes up with

du: cannot access fake.txt': No such file or directory stat: cannot stat fake.txt': No such file or directory stat: cannot stat `fake.txt': No such file or directory date: fake.txt: No such file or directory

what am I missing?

REDO:

#!/bin/csh

echo Enter file name
set filename = $<

endif
test -f $filename

if ( $status == 0 ) then
        if(-z $filename)then
        rm $filename

        else
        clear
        echo $filename
        du -sh $filename
        stat -c %h $filename
        stat -c %U $filenam
        endif
else
  echo "File is not an ordinary file."
endif

There is a much easier way to determine if a file is a regular file (and exists):

#!/bin/csh

echo "Enter filename: "
set filename = $<
test -f $filename

if ( $status == 0 ) then
  echo "File is an ordinary file."
else
  echo "File is not an ordinary file."
endif

# end of file.

Details on how test(1) works can be found from an appropriate manual page. In this example I've simply used the fact that test(1) exits with a non-zero exit code in case the test condition used is not fulfilled: switch -f tests that the argument given exists and is a regular file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM