tags:

views:

39

answers:

2

I need a way to make a process keep a certain file open forever. Here's an example of what I have so far:

sleep 1000 > myfile &

It works for a thousand seconds, but really don't want to make some complicated sleep/loop statement. This post suggested that cat is the same thing as sleep for infinite. So I tried this:

cat > myfile &

It almost looks like a mistake doesn't it? It seemed to work from the command line, but in a script the file connection did not stay open. Any other ideas?

+1  A: 
tail -f myfile

This 'follows' the file, and outputs any changes to the file. If you don't want to see the output of tail, redirect output to /dev/null or something:

tail -f myfile > /dev/null

You may want to use the --retry option, depending on your specific case. See man tail for more information.

strager
This won't do what he wants, which is keep the file open for writing. It will merely read from it.
DVK
@DVK, He said 'keep the file open', not 'for writing'.
strager
@strager: No, but the `> myfile` implies that he meant writing.
Dennis Williamson
+4  A: 

The reason that cat>myfile& works is because it re-directs standard input into a file.

if you launch it with an ampersand (in background), it won't get ANY input, including end-of-file, which means it will forever wait and print nothing to the output file.

You can get an equivalent effect, except WITHOUT dependency on standard input (the latter is what makes it not work in your script), with this command:

tail -f /dev/null > myfile &
DVK
That worked! I still don't understand why the `cat` worked on terminal but not in a script. On the terminal, I get a notification of "Stopped" and the script doesn't not give me this. That must be part of the reason.
User1
@User1 - I can speculate on why cat didn't work but to be honest I don't know 100% for sure. Some sort of weird SDTIN and tty interaction, probably. Feel free to ask that as a separate question if you're really interested, I'm sure someone will know the asnwer with certainty and I'd be curious too - no time to investigate mysefl.
DVK