home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


UNIX Power Tools

UNIX Power ToolsSearch this book
Previous: 45.9 The Unappreciated Bourne Shell  ":" Operator Chapter 45
Shell Programming for the Initiated
Next: 45.11 The Multipurpose jot Command
 

45.10 Removing a File Once It's Opened - for Security and Easy Cleanup

Once a process has opened a file ( 45.20 ) , UNIX won't delete the file until the process closes it. (The rm command only removes a link to the file from a directory, not the file itself.)

I've heard arguments ( 24.3 ) about whether removing a file while it's open is a good idea. If you want to run a set of commands from a file, but not let anyone else read the list of commands you're using, you can write a shell script that removes itself before doing anything else. (You should be aware that if you use a filesystem mounted by NFS ( 1.33 ) , NFS will just rename the "removed" file to a hidden filename ( 16.11 ) like .nfsXXXXX .)

Here's a simple self-removing shell script:

% 

cat doit


rm doit   # by now, shell has opened this file; we can remove it
ls doit
make bigprog
   ...
% 

sh doit


ls: doit not found
cc   -target sun4 -c  routine.c
   ...

Here's a more typical script that opens and removes a file in /tmp ( 21.3 ) :









exec
 






<&-
 









% 

cat delme


#!/bin/sh
temp=/tmp/delme$$              # file in /tmp (could be anywhere)
echo "This is line1.
This is line2.
This is line3." > $temp        # put three lines in $temp
ls -l $temp; wc $temp          # ls and count lines in the file


exec < $temp                   # take standard input from $temp
read line; echo $line          # read and echo line 1 from $temp
rm $temp; echo rm returned $?  # remove $temp link; show status
ls -l $temp; wc $temp          # the file is gone...?
read line; echo $line          # but file is still open!
read line; echo $line
exec <&-                       # close standard input (and file)
% 

delme


-rw-rw-r--   1 jerry    45 Sep 16 12:31 /tmp/delme22743
      3      9     45 /tmp/delme22743
This is line1.
rm returned 0
ls: /tmp/delme22743: No such file or directory
wc: cannot open /tmp/delme22743
This is line2.
This is line3.

- JP


Previous: 45.9 The Unappreciated Bourne Shell  ":" Operator UNIX Power Tools Next: 45.11 The Multipurpose jot Command
45.9 The Unappreciated Bourne Shell ":" Operator Book Index 45.11 The Multipurpose jot Command

The UNIX CD Bookshelf Navigation The UNIX CD BookshelfUNIX Power ToolsUNIX in a NutshellLearning the vi Editorsed & awkLearning the Korn ShellLearning the UNIX Operating System