Shell Script For Deleting Files

This code, which we will call Del, will delete files like rm does, prompting for your confirmation for each file to be deleted, including directory files (which the -i option of rm won’t do).

#!  /bin/csh  -f

foreach name ($argv) if ( -f $name ) then

echo -n "delete the file ’${name}’ (y/n/q)?" else

echo -n "delete the entire directory ’${name}’ (y/n/q)? " endif

set  ans  =  $< switch  ($ans) case  n:

continue case q:

exit case y:

rm -r $name continue

endsw

end

(Before reading further, try this program yourself.  Set up a test directory, with several files in it, at least one of which is a subdirectory, with at least one file there. Then type ‘Del *’.)

The line

if  (  -f  $name  )  then

tests to see if the file whose name is in $name is an ordinary file, as opposed to a directory file.

The -n option of echo tells the shell not to print the newline character, so that our answer, y/n/q, will be on the same line.

In the line

set  ans  =  $<

the symbol ‘$<’ means the input from the keyboard.

The keyword ‘continue’ means to go to the top of the enclosing loop.

The -r option of the rm command means that if an argument is a directory, then remove that directory, and all the files (and subdirectories, etc.) within it.

Unix Tips

See Also
Gzip More Than One File and Deleting First Line

Have a Unix Problem
Unix Forum - Do you have a UNIX Question?

Unix Books :-
UNIX Programming, Certification, System Administration, Performance Tuning Reference Books

Return to : - Unix System Administration Hints and Tips

(c) www.gotothings.com All material on this site is Copyright.
Every effort is made to ensure the content integrity.  Information used on this site is at your own risk.
All product names are trademarks of their respective companies.
The site www.gotothings.com is in no way affiliated with or endorsed by any company listed at this site.
Any unauthorised copying or mirroring is prohibited.