What happens when I delete a file being used through input redirection?

Go To StackoverFlow.com

1

On linux, I am loading a file into a database using psql and the input redirection operator. I would like to delete the file in order to free up some disk space. Will that interfere with the load?

psql mydatabase < myfile.sql &
rm myfile.sql
2012-04-05 15:45
by Stanish


3

The file won't actually be deleted from the disk until psql has finished. It'll be deleted from the directory so it won't appear, but the file will remain on disk (using up space), until the operation has completed.

2012-04-05 15:48
by Douglas Leeder
How do you know that the psql command will have opened the file handle to myfile.sql before rm unlinks it - Andrew Tomazos 2012-04-05 15:51
@user1131467: Because the shell must have completed the I/O redirection before it can put the psql process in the background - Aaron Digulla 2012-04-05 16:00


1

In linux (and most unix variants) deleting a file that a process currently holds open will cause the OS to delete the directory entry, but keep the file itself on disk until the last process holding the file open closes it, so processes using the file can happily work away as if nothing has happened.

So (1) your script works by lucky coincidence (the shell also does not remove the file until it has set up the redirect), and (2) attempting to remove the file before psql has finished using it achieves little, as the file will still take up disk space until psql finishes.

What you probably mean to do is:

(psql mydatabase < myfile.sql && rm myfile.sql) &

This like spawns a subshell in the background, which runs the psql command and after it returns remove myfile.sql.

The && means "run the left side, and only if it is successful (read: returns exit status 0) run the right side". This is a common shell idiom.

2012-04-05 18:39
by Michael Slade
Ads