Keep a file open forever within a bash script

Viewed 11357

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?

4 Answers

Rather than using a background process, you can also just use bash to open one of its file descriptors:

exec 5>myfile 

(The special use of exec here allows changing the current file descriptor redirections - see man bash for details). This will open file descriptor 5 to "myfile" (use >> if you don't want to empty the file).

You can later close the file again with:

exec 5>&-

(One possible downside of this is that the FD gets inherited by every program that the shell runs in the meantime. Mostly this is harmless - e.g. your greps and seds will generally ignore the extra FD - but it could be annoying in some cases, especially if you spawn any processes that stay around (because they will then keep the FD open).

Note: If you are using a newer version of bash (>4.1) you can use a slightly different syntax:

exec {fd}>myfile

This allocates a new file descriptor, and puts it in the variable fd. This can help ensure that scripts don't accidentally overwrite each other's file descriptors. To close the file later, use

exec {fd}>&-
Related